package com.css.fxfzypg.modules.resultManagement.reportManagement.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.annotation.AddData;
import com.css.fxfzypg.base.annotation.CompareAndSwap;
import com.css.fxfzypg.base.annotation.Transform;
import com.css.fxfzypg.base.annotation.TransformV2;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.manage.building.repository.BuildingReqository;
import com.css.fxfzypg.manage.building.repository.entity.BuildingEntity;
import com.css.fxfzypg.manage.building.vo.BuildingEntityVO;
import com.css.fxfzypg.manage.building.vo.BuildingResultVo;
import com.css.fxfzypg.manage.lethalitydifference.vo.SysMenuVo;
import com.css.fxfzypg.manage.sampling.repository.SamplingReqository;
import com.css.fxfzypg.manage.sampling.repository.entity.SamplingEntity;
import com.css.fxfzypg.modules.SettingSeismic.entity.SettingSeismicPoint;
import com.css.fxfzypg.modules.SettingSeismic.repository.impl.SettingSeismicRepositoryImpl;
import com.css.fxfzypg.modules.SettingSeismic.vo.SettingSeismicDetailsVO;
import com.css.fxfzypg.modules.baseData.entity.*;
import com.css.fxfzypg.modules.baseData.queryParams.AirportQueryParams;
import com.css.fxfzypg.modules.baseData.queryParams.RoadQueryParams;
import com.css.fxfzypg.modules.baseData.repository.*;
import com.css.fxfzypg.modules.baseData.service.*;
import com.css.fxfzypg.modules.baseData.service.impl.DrillService;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.TrafficAnalysis;
import com.css.fxfzypg.modules.earthquakedisasterloss.entity.YpgResultRoad;
import com.css.fxfzypg.modules.earthquakedisasterloss.repository.CountLandslideRepository;
import com.css.fxfzypg.modules.earthquakedisasterloss.service.CountLandslideService;
import com.css.fxfzypg.modules.maps.service.*;
import com.css.fxfzypg.modules.message.repository.entity.MessageEntity;
import com.css.fxfzypg.modules.message.service.MessageService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.service.PreAssessTaskService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.VO.*;
import com.css.fxfzypg.modules.resultManagement.reportManagement.entity.*;
import com.css.fxfzypg.modules.resultManagement.reportManagement.handle.ReportHandle;
import com.css.fxfzypg.modules.resultManagement.reportManagement.repository.ReportManagementRepository;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportDataService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.service.ReportManagementService;
import com.css.fxfzypg.modules.resultManagement.reportManagement.ypg.*;
import com.css.fxfzypg.modules.resultsManagement.service.MapManagementService;
import com.css.fxfzypg.modules.resultupload.repository.ResultRepository;
import com.css.fxfzypg.modules.resultupload.repository.ResultTotalRepository;
import com.css.fxfzypg.modules.resultupload.repository.entity.PrefectureResultEntity;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultEntity;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.modules.resultupload.vo.ResultMainEntityVO;
import com.css.fxfzypg.modules.spatialData.repository.BoundaryNativeRepository;
import com.css.fxfzypg.modules.spatialData.repository.entity.BoundaryEntity;
import com.css.fxfzypg.modules.suggestinfo.analysis.annualrisk.repository.entity.AnnualRiskEntity;
import com.css.fxfzypg.modules.suggestinfo.analysis.annualrisk.service.AnnualRiskService;
import com.css.fxfzypg.modules.suggestinfo.analysis.disasterscenario.repository.entity.DisasterScenarioEntity;
import com.css.fxfzypg.modules.suggestinfo.analysis.emergencydisaster.repository.entity.EmergencyDisasterEntity;
import com.css.fxfzypg.modules.suggestinfo.analysis.emergencydisposal.repository.entity.EmergencyDisposalEntity;
import com.css.fxfzypg.modules.suggestinfo.analysis.suggestionanalysis.repository.SuggestionAnalysisRepository;
import com.css.fxfzypg.modules.suggestinfo.analysis.suggestionanalysis.service.SuggestionAnalysisService;
import com.css.fxfzypg.modules.surveytaskmanage.repository.FieldSurveyTaskRepository;
import com.css.fxfzypg.modules.surveytaskmanage.service.FieldSurveyTaskService;
import com.css.fxfzypg.modules.test.CustomXWPFDocument;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysOrgService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.*;
import com.deepoove.poi.plugin.table.HackLoopTableRenderPolicy;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.Table;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2022年10月08日  14:35
 */
@Service
public class ReportManagementServiceImpl implements ReportManagementService {

    @Value("${image.localDir}")
    private String localDir;

    @Autowired
    MessageService messageService;

    @Resource
    HistoricalSeismicDataRepository historicalSeismicDataRepository;

    @Autowired
    ResultRepository resultRepository;

    @Autowired
    SuggestionAnalysisService suggestionAnalysisService;

    @Resource
    private ReportManagementRepository reportManagementRepository;
    @Resource
    BoundaryNativeRepository boundaryNativeRepository;

    @Resource
    private PreAssessTaskRepository preAssessTaskRepository;

    @Resource
    private PreAssessTaskService preAssessTaskService;

    @Resource
    MapManagementService mapManagementService;

    @Resource
    HistoricalSeismicDataService historicalSeismicDataService;

    @Resource
    SUserService sUserService;

    @Resource
    SysOrgService sysOrgService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    ResultTotalRepository resultTotalRepository;

    @Resource
    SettingSeismicRepositoryImpl settingSeismicRepository;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Resource
    private SysAreaService sysAreaService;

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private CountiesConditionRepository countiesConditionRepository;

    @Resource
    private HosPeoRepository hosPeoRepository;

    @Resource
    GdpRepositpory gdpRepositpory;

    @Resource
    BuildingReqository buildingReqository;

    @Autowired
    FieldSurveyTaskRepository fieldSurveyTaskRepository;

    @Resource
    CountLandslideService countLandslideService;

    @Resource
    RiskEnterpriseDataService riskEnterpriseDataService;

    @Resource
    RiskEnterpriseMapService riskEnterpriseMapService;

    @Resource
    private GasstationDataMapService gasstationDataMapService;

    @Resource
    GasstationDataService gasstationDataService;


    @Resource
    SeismicSetoutRepository seismicSetoutRepository;


    @Resource
    SeismicSetoutService seismicSetoutService;

    @Resource
    private ReservoirMapService reservoirMapService;

    @Resource
    private SchoolMapService schoolMapService;

    @Resource
    private GeologicalMapService geologicalMapService;

    @Resource
    private ReportDataService reportDataService;

    @Resource
    private CountLandslideRepository countLandslideRepository;

    @Resource
    private CountLandslideMapService countLandslideMapService;

    @Resource
    private RiskEnterpriseDataRepository riskEnterpriseDataRepository;

    @Resource
    private SuggestionAnalysisRepository suggestionAnalysisRepository;

    @Resource
    private AnnualRiskService annualRiskService;

    @Resource
    SamplingReqository samplingReqository;

    @Resource
    private VillageTownHosPeoRepository villageTownHosPeoRepository;

    @Resource
    private VillageTownConditionRepository villageTownConditionRepository;

    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;

    @Resource
    ReportHandle reportHandle;

    @Resource
    RestTemplate restTemplate;

    @Resource
    RoadMapService roadMapService;
    @Resource
    AirportMapService airportMapService;
    @Resource
    AreaMapService areaMapService;

    @Resource
    DrillService drillService;

    @Resource
    private AreaRepository areaRepository;
    @Autowired
    FieldSurveyTaskService fieldSurveyTaskService;

    @Override
    public Map<String, Object> getPage(ReportManagementVO vo, int curPage, int pageSize) {
        vo.setCreateUser(PlatformSessionContext.getUserID());
        Map<String, Object> data = reportManagementRepository.findParentTask("0", vo, curPage, pageSize);
        List<ReportManagementVO> list = (List<ReportManagementVO>) data.get("rows");
        List<ReportManagementVO> rList = new ArrayList<>();
        for (ReportManagementVO reportManagementVO : list) {
            String reportId = reportManagementVO.getReportId();
            //获取审核不通过建议
            String reviewOpinion = reportManagementRepository.getReviewOpinion(reportId);
            reportManagementVO.setReviewOpinion(reviewOpinion);
            rList.add(reportManagementVO);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", rList);
        map.put("total", data.get("total"));
        return map;
    }

    @Override
    public ReportManagement getReportByTaskId(String taskId) {
        return reportManagementRepository.getReportByTaskId(taskId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReportManagement createReport(String taskId, String type, String level, String dataSource, String simplifiedReportTemplate, String DeReportTemplate, String attachId, HttpServletResponse response) throws Exception {
        //    List<PreAssessTaskEntity> subTask = preAssessTaskService.getSubTask("0");
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);
        if (PlatformObjectUtils.isEmpty(preAssessTaskEntity)) {
            throw new RuntimeException("查询不到任务信息");
        }
        ReportManagement report = reportManagementRepository.getReportByTaskId(taskId);
        //1 生成报告的逻辑
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(attachId);
        if (attach == null) {
            throw new RuntimeException("查询不到模板信息");
        }
        String fileDirId = attach.getFileDirId();
        String attachPath = attach.getAttachPath();
//        ClassPathResource classPathResource = new ClassPathResource("static/report.docx");
        ZipSecureFile.setMinInflateRatio(-1D);
        FileInputStream fileInputStream = new FileInputStream(fileDirId + attachPath);
        //FileInputStream fileInputStream = new FileInputStream("D:\\公司文档数据\\预评估\\报告模板\\预评估报告简本模板_版本二_带水印_20230825.docx");
        CustomXWPFDocument xwpfDocument = new CustomXWPFDocument(fileInputStream);
        if (StringUtils.isBlank(dataSource)) {
            dataSource = "2";
        }
        Map reportData = getReportData(preAssessTaskEntity, dataSource, level, simplifiedReportTemplate);
        if (simplifiedReportTemplate.contains("版本一")) {
            createReport(xwpfDocument, reportData);
        } else {
            createReportVersion2(xwpfDocument, reportData);
        }

        OutputStream os = null;
        //String fileName = "模板.docx";
        StringBuilder fileName = new StringBuilder();
        String taskName = preAssessTaskEntity.getTaskName();
        fileName.append(taskName);
        //1、简本 2、详本
        String temp = "";
        if ("1".equals(type)) {
            temp = "简本";
        } else {
            temp = "详本";
        }
        fileName.append("_").append(temp);
        LocalDateTime now = LocalDateTime.now();
        //yyyy-MM-dd-HH:mm:ss
        String nowFormat = now.format(DateTimeFormatter.ofPattern("yyyy-MM-ddHH-mm-ss"));
        fileName.append("(").append(nowFormat).append(").docx");
        os = new FileOutputStream(localDir + File.separator + fileName);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        xwpfDocument.write(os);
        fileInputStream.close();
        os.flush();
        os.close();
        String defaultSimpleReportName = "";
        String defaultMinuteReportName = "";
        if ("1".equals(type)) {
            defaultSimpleReportName = fileName.toString();
        } else {
            defaultMinuteReportName = fileName.toString();
        }
        ReportManagement reportManagement = new ReportManagement();
        String reportId = "";
        if (PlatformObjectUtils.isNotEmpty(report.getId())) {
            //该任务已经存在过报告附件则更新 否则新增
            reportId = report.getId();
            reportManagement.setId(report.getId());
            reportManagement.setDefaultSimpleReportName(defaultSimpleReportName);
            reportManagement.setDefaultMinuteReportName(defaultMinuteReportName);
            reportManagement.setDeReportTemplate(DeReportTemplate);
            reportManagement.setSimplifiedReportTemplate(simplifiedReportTemplate);
            reportManagement.setDataSource(dataSource);
            reportManagementRepository.update(reportManagement);
        } else {
            //新增报告附件
            reportId = UUIDGenerator.getUUID();
            preAssessTaskRepository.insertReportId(taskId, reportId);
            reportManagement.setId(reportId);
            reportManagement.setReportStatus("1");
            reportManagement.setDefaultSimpleReportName(defaultSimpleReportName);
            reportManagement.setDefaultMinuteReportName(defaultMinuteReportName);
            reportManagement.setReportCreateUserId(PlatformSessionContext.getUserID());
            reportManagement.setReportCreateTime(new Date());
            reportManagement.setAdministrativeLevel(level);
            reportManagement.setReportPath(localDir);
            reportManagement.setDataSource(dataSource);
            reportManagement.setDeReportTemplate(DeReportTemplate);
            reportManagement.setSimplifiedReportTemplate(simplifiedReportTemplate);
            reportManagementRepository.save(reportManagement);
        }
        //同步产品服务
        transReportMsgToCpxx(localDir+File.separator+defaultSimpleReportName,defaultSimpleReportName,taskName+","+"简本");
        return reportManagementRepository.getReportById(reportId);
    }

    private void createReportVersion2(CustomXWPFDocument doc, Map params) {
        //替换段落字段和图片
        replaceInPara(doc, params);
        createTableV2(doc, params);
    }

    //生成报告
    private void createReport(CustomXWPFDocument doc, Map<String, Object> params) throws IOException {
        //替换段落字段和图片
        replaceInPara1(doc, params);
        //创建表格
        createTable(doc, params);
    }

    public void center(XWPFTableCell cell) {
        CTTc ctTc = cell.getCTTc();
        CTTcPr ctTcPr = ctTc.addNewTcPr();
        ctTcPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        CTTcBorders border = ctTcPr.addNewTcBorders();
        border.addNewBottom().setVal(STBorder.SINGLE);
        border.addNewRight().setVal(STBorder.SINGLE);
        border.addNewLeft().setVal(STBorder.SINGLE);
        border.addNewTop().setVal(STBorder.SINGLE);
        ctTc.getPList().get(0).addNewPPr().addNewJc().setVal(STJc.CENTER);
    }

    public static String setWordValue(String value, Map<String, String> textMap) {
        Set<Map.Entry<String, String>> textSets = textMap.entrySet();
        for (Map.Entry<String, String> textSet : textSets) {
            String key = "${" + textSet.getKey() + "}";
            if (value.indexOf(key) != -1) {
                value = value.replace(key, textSet.getValue());
            }
        }
        return value;
    }

    private void createTableV2(CustomXWPFDocument doc, Map<String, Object> params) {
        Map<String, List<List<String>>> prefectureResultEntityMap = (Map<String, List<List<String>>>) params.get("prefectureResultEntityList");
        List<Map<String, List<List<String>>>> keyDisaterStaticsList = (List<Map<String, List<List<String>>>>) params.get("keyDisaterStaticsList");
        List<List<String>> suggestionList = (List<List<String>>) params.get("suggestionList");
        List<List<String>> riskList = (List<List<String>>) params.get("riskList");
        List<List<String>> disposalList = (List<List<String>>) params.get("disposalList");
        Map<String, List<List<String>>> resultEntityMap = (Map<String, List<List<String>>>) params.get("resultEntityList");
        List<Map<String, List<List<String>>>> cityStructureList = (List<Map<String, List<List<String>>>>) params.get("townStructureList");
        List<Map<String, List<List<String>>>> villageStructureList = (List<Map<String, List<List<String>>>>) params.get("villageStructureList");
        Map<String, List<StructureType>> provinceGroupList = (Map<String, List<StructureType>>) params.get("provinceGroupList");
        List<Map<String, List<List<String>>>> analysisAllList = (List<Map<String, List<List<String>>>>) params.get("analysisAllList");
        List<Map<String, List<List<String>>>> hosStrList = (List<Map<String, List<List<String>>>>) params.get("hosStrList");
        Map<String, List<HosPeo>> provinceHosList = (Map<String, List<HosPeo>>) params.get("provincePeoList");
        String level = (String) params.get("level");
        List<XWPFTable> tables = doc.getTables();
        for (int ii = 0; ii < tables.size(); ii++) {
            if (ii == 0) {
                XWPFTable table = tables.get(ii);
                int t = 0;
                if ("1".equals(level)) {
                    List<XWPFTableCell> cells = table.getRows().get(0).getTableCells();
                    List<String> headList = new ArrayList<>();
                    headList.add("市、州");
                    headList.add("重点地区");
                    headList.add("震级");
                    headList.add("死亡人数（人）");
                    headList.add("受伤人数（人）");
                    headList.add("需紧急安置人数（万人） ");
                    headList.add("需救援力量（人） ");
                    headList.add("需帐篷数量（万顶） ");
                    for (int j = 0; j < cells.size(); j++) {
                        XWPFTableCell cell = cells.get(j);
                        center(cell);
                        setTableHeadFontSize(headList.get(j), cell);
                    }
                } else {
                    List<XWPFTableCell> cells = table.getRows().get(0).getTableCells();
                    List<String> headList = new ArrayList<>();
                    headList.add("区、县");
                    headList.add("重点地区");
                    headList.add("震级");
                    headList.add("死亡人数（人）");
                    headList.add("受伤人数（人）");
                    headList.add("需紧急安置人数（人） ");
                    headList.add("需救援力量（人） ");
                    headList.add("需帐篷数量（顶） ");
                    for (int j = 0; j < cells.size(); j++) {
                        XWPFTableCell cell = cells.get(j);
                        center(cell);
                        setTableHeadFontSize(headList.get(j), cell);
                    }
                }
                if (PlatformObjectUtils.isNotEmpty(prefectureResultEntityMap) && prefectureResultEntityMap.values().size() > 0) {
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    Iterator<Map.Entry<String, List<List<String>>>> iterator = prefectureResultEntityMap.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<List<String>>> next = iterator.next();
                        String key = next.getKey();
                        List<List<String>> value = next.getValue();
                        int size = value.size();
                        for (int i = 0; i < size; i++) {
                            table.createRow();
                        }
                        tempIndex = startIndex;
                        List<XWPFTableRow> rows = table.getRows();
                        for (int i = 1; i <= size; i++) {
                            XWPFTableRow newRow = table.getRow(startIndex);
                            //copyStyle(newRow, header);
                            List<XWPFTableCell> cells = newRow.getTableCells();
                            for (int j = 0; j < cells.size(); j++) {
                                XWPFTableCell cell = cells.get(j);
                                List<String> strList = value.get(i - 1);
                                for (; t < strList.size(); t++) {
                                    center(cell);
                                    setTableFontSize(strList.get(t), cell);
                                    t++;
                                    break;
                                }
                            }
                            t = 0;
                            startIndex++;
                        }
                        //合并单元格
                        for (int rowIndex = tempIndex; rowIndex < rows.size(); rowIndex++) {
                            for (int zz = 0; zz < 2; zz++) {
                                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(zz);
                                if (mergeCell1 != null) {
                                    if (rowIndex == tempIndex) {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                    } else {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                    center(mergeCell1);
                                }
                            }
                        }
                    }


                }
            } else if (ii == 1) {
                XWPFTable table = tables.get(ii);
                int t = 0;
                if (PlatformObjectUtils.isNotEmpty(keyDisaterStaticsList)) {
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    for (Map<String, List<List<String>>> map : keyDisaterStaticsList) {
                        Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<List<String>>> next = iterator.next();
                            String key = next.getKey();
                            List<List<String>> value = next.getValue();
                            int size = value.size();
                            for (int i = 0; i < size; i++) {
                                table.createRow();
                            }
                            tempIndex = startIndex;
                            List<XWPFTableRow> rows = table.getRows();
                            for (int i = 1; i <= size; i++) {
                                XWPFTableRow newRow = table.getRow(startIndex);
                                List<XWPFTableCell> cells = newRow.getTableCells();
                                for (int j = 0; j < cells.size(); j++) {
                                    XWPFTableCell cell = cells.get(j);
                                    List<String> strList = value.get(i - 1);
                                    for (; t < strList.size(); t++) {
                                        center(cell);
                                        setTableFontSize(strList.get(t), cell);
                                        t++;
                                        break;
                                    }
                                }
                                t = 0;
                                startIndex++;
                            }
                            //合并单元格
                            mergeCell(tempIndex, rows.size(), table, 1, 0);
                        }
                    }
                }
            } else if (ii == 3) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(suggestionList)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    int size = suggestionList.size();
                    for (int i = 0; i < size; i++) {
                        table.createRow();
                    }
                    tempIndex = startIndex;
                    //List<XWPFTableRow> rows = table.getRows();
                    for (int i = 1; i <= size; i++) {
                        XWPFTableRow newRow = table.getRow(startIndex);
                        List<XWPFTableCell> cells = newRow.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            List<String> strList = suggestionList.get(i - 1);
                            for (; t < strList.size(); t++) {
                                center(cell);
                                setTableFontSize(strList.get(t), cell);
                                t++;
                                break;
                            }
                        }
                        t = 0;
                        startIndex++;
                    }
                }
            } else if (ii == 4) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(riskList)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    int size = riskList.size();
                    for (int i = 0; i < size; i++) {
                        table.createRow();
                    }
                    tempIndex = startIndex;
                    //List<XWPFTableRow> rows = table.getRows();
                    for (int i = 1; i <= size; i++) {
                        XWPFTableRow newRow = table.getRow(startIndex);
                        List<XWPFTableCell> cells = newRow.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            List<String> strList = riskList.get(i - 1);
                            for (; t < strList.size(); t++) {
                                center(cell);
                                setTableFontSize(strList.get(t), cell);
                                t++;
                                break;
                            }
                        }
                        t = 0;
                        startIndex++;
                    }
                }
            } else if (ii == 5) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(disposalList)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    int size = disposalList.size();
                    for (int i = 0; i < size; i++) {
                        table.createRow();
                    }
                    tempIndex = startIndex;
                    //List<XWPFTableRow> rows = table.getRows();
                    for (int i = 1; i <= size; i++) {
                        XWPFTableRow newRow = table.getRow(startIndex);
                        List<XWPFTableCell> cells = newRow.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            List<String> strList = disposalList.get(i - 1);
                            for (; t < strList.size(); t++) {
                                center(cell);
                                setTableFontSize(strList.get(t), cell);
                                t++;
                                break;
                            }
                        }
                        t = 0;
                        startIndex++;
                    }
                }
            } else if (ii == 6) {
                XWPFTable table = tables.get(ii);
                if ("1".equals(level)) {
                    for (int db = 0; db < 2; db++) {
                        List<XWPFTableCell> cells = table.getRows().get(db).getTableCells();
                        List<String> headList = new ArrayList<>();
                        headList.add("序号");
                        headList.add("震中经度");
                        headList.add("震中纬度");
                        headList.add("宏观位置");
                        headList.add("震级");
                        headList.add("受灾区域面积（平方公里）");
                        headList.add("灾区人口（万人） ");
                        headList.add("灾区范围内GDP（亿） ");
                        if (db == 0) {
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                        } else if (db == 1) {
                            headList.add("预估死亡（人）");
                            headList.add("预估受伤（人）");
                            headList.add("需紧急安置（万人）");
                            headList.add("需应急处置队伍（人）");
                            headList.add("预估需帐篷（万顶）");
                        }
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            center(cell);
                            setTableHeadFontSize(headList.get(j), cell);
                        }
                    }
                } else {
                    for (int db = 0; db < 2; db++) {
                        List<XWPFTableCell> cells = table.getRows().get(db).getTableCells();
                        List<String> headList = new ArrayList<>();
                        headList.add("序号");
                        headList.add("震中经度");
                        headList.add("震中纬度");
                        headList.add("宏观位置");
                        headList.add("震级");
                        headList.add("受灾区域面积（平方公里）");
                        headList.add("灾区人口（万人） ");
                        headList.add("灾区范围内GDP（亿） ");
                        if (db == 0) {
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                            headList.add("评估结果");
                        } else if (db == 1) {
                            headList.add("预估死亡（人）");
                            headList.add("预估受伤（人）");
                            headList.add("需紧急安置（人）");
                            headList.add("需应急处置队伍（人）");
                            headList.add("预估需帐篷（顶）");
                        }
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            center(cell);
                            setTableHeadFontSize(headList.get(j), cell);
                        }
                    }
                }
                if (PlatformObjectUtils.isNotEmpty(resultEntityMap)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 2;
                    int tempIndex = 1;
                    Iterator<Map.Entry<String, List<List<String>>>> iterator = resultEntityMap.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, List<List<String>>> next = iterator.next();
                        String key = next.getKey();
                        List<List<String>> value = next.getValue();
                        int size = value.size();
                        for (int i = 0; i < size; i++) {
                            table.createRow();
                        }
                        tempIndex = startIndex;
                        List<XWPFTableRow> rows = table.getRows();
                        for (int i = 2; i <= (size + 1); i++) {
                            XWPFTableRow newRow = table.getRow(startIndex);
                            //copyStyle(newRow, header);
                            List<XWPFTableCell> cells = newRow.getTableCells();
                            for (int j = 0; j < cells.size(); j++) {
                                XWPFTableCell cell = cells.get(j);
                                List<String> strList = value.get(i - 2);
                                for (; t < strList.size(); t++) {
                                    center(cell);
                                    setTableFontSize(strList.get(t), cell);
                                    t++;
                                    break;
                                }
                            }
                            t = 0;
                            startIndex++;
                        }
                        //合并单元格
                        for (int rowIndex = tempIndex; rowIndex < rows.size(); rowIndex++) {
                            for (int j = 0; j < 4; j++) {
                                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                                if (mergeCell1 != null) {
                                    if (rowIndex == tempIndex) {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                    } else {
                                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                    }
                                    center(mergeCell1);
                                }
                            }
                        }
                    }

                    //合并表头 行合并
                    for (int rowIndex = 0; rowIndex < 2; rowIndex++) {
                        for (int j = 0; j < 8; j++) {
                            XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                            if (mergeCell1 != null) {
                                if (rowIndex == 0) {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                } else {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                }
                                center(mergeCell1);
                            }
                        }
                    }
                    //合并表头 列合并
                    for (int cellIndex = 8; cellIndex <= 12; cellIndex++) {
                        XWPFTableCell cell = table.getRow(0).getCell(cellIndex);
                        if (cellIndex == 8) {
                            // The first merged cell is set with RESTART merge value
                            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                        } else {
                            // Cells which join (merge) the first one, are set with CONTINUE
                            cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                        }
                        center(cell);
                    }
                }
            } else if (ii == 7) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(cityStructureList)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    int fromIndex = 1;
                    for (Map<String, List<List<String>>> map : cityStructureList) {
                        Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<List<String>>> next = iterator.next();
                            String key = next.getKey();
                            List<List<String>> value = next.getValue();
                            int size = value.size();
                            for (int i = 0; i < size; i++) {
                                table.createRow();
                            }
                            tempIndex = startIndex;
                            List<XWPFTableRow> rows = table.getRows();
                            for (int i = 1; i <= size; i++) {
                                XWPFTableRow newRow = table.getRow(startIndex);
                                List<XWPFTableCell> cells = newRow.getTableCells();
                                for (int j = 0; j < cells.size(); j++) {
                                    XWPFTableCell cell = cells.get(j);
                                    List<String> strList = value.get(i - 1);
                                    for (; t < strList.size(); t++) {
                                        center(cell);
                                        setTableFontSize1(strList.get(t), cell);
                                        t++;
                                        break;
                                    }
                                }
                                t = 0;
                                startIndex++;
                            }
                            //合并单元格
                            mergeCell(tempIndex, rows.size(), table, 2, 1);
                            List<StructureType> structureTypes = provinceGroupList.get(key.split("_")[0]);
                            if (structureTypes.size() > 1) {
                                mergeProvinceCell(fromIndex, structureTypes.size(), table, 1, 0);
                                fromIndex = structureTypes.size() - 1;
                            }
                        }
                    }
                }
            } else if (ii == 8) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(villageStructureList)) {
                    int t = 0;
                    int fromIndex = 1;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    for (Map<String, List<List<String>>> map : villageStructureList) {
                        Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<List<String>>> next = iterator.next();
                            String key = next.getKey();
                            List<List<String>> value = next.getValue();
                            int size = value.size();
                            for (int i = 0; i < size; i++) {
                                table.createRow();
                            }
                            tempIndex = startIndex;
                            List<XWPFTableRow> rows = table.getRows();
                            for (int i = 1; i <= size; i++) {
                                XWPFTableRow newRow = table.getRow(startIndex);
                                List<XWPFTableCell> cells = newRow.getTableCells();
                                for (int j = 0; j < cells.size(); j++) {
                                    XWPFTableCell cell = cells.get(j);
                                    List<String> strList = value.get(i - 1);
                                    for (; t < strList.size(); t++) {
                                        center(cell);
                                        setTableFontSize1(strList.get(t), cell);
                                        t++;
                                        break;
                                    }
                                }
                                t = 0;
                                startIndex++;
                            }
                            //合并单元格
                            mergeCell(tempIndex, rows.size(), table, 2, 1);
                            List<StructureType> structureTypes = provinceGroupList.get(key.split("_")[0]);
                            if (structureTypes.size() > 0) {
                                mergeProvinceCell(fromIndex, structureTypes.size(), table, 1, 0);
                                fromIndex = structureTypes.size() - 1;
                            }
                        }
                    }
                }
            } else if (ii == 9) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(analysisAllList)) {
                    int t = 0;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    for (Map<String, List<List<String>>> map : analysisAllList) {
                        Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<List<String>>> next = iterator.next();
                            String key = next.getKey();
                            List<List<String>> value = next.getValue();
                            int size = value.size();
                            for (int i = 0; i < size; i++) {
                                table.createRow();
                            }
                            tempIndex = startIndex;
                            List<XWPFTableRow> rows = table.getRows();
                            for (int i = 1; i <= size; i++) {
                                XWPFTableRow newRow = table.getRow(startIndex);
                                List<XWPFTableCell> cells = newRow.getTableCells();
                                for (int j = 0; j < cells.size(); j++) {
                                    XWPFTableCell cell = cells.get(j);
                                    List<String> strList = value.get(i - 1);
                                    for (; t < strList.size(); t++) {
                                        center(cell);
                                        if (t == 4) {
                                            setCellImage(cell, strList.get(t));
                                        } else {
                                            setTableFontSize(strList.get(t), cell);
                                        }
                                        t++;
                                        break;
                                    }
                                }
                                t = 0;
                                startIndex++;
                            }
                            //合并单元格
                            mergeCell(tempIndex, rows.size(), table, 1, 0);
                        }
                    }
                }
            } else if (ii == 10) {
                XWPFTable table = tables.get(ii);
                if (PlatformObjectUtils.isNotEmpty(hosStrList)) {
                    int t = 0;
                    int fromIndex = 1;
                    //记录初始下标
                    int startIndex = 1;
                    int tempIndex = 1;
                    Map<String, Integer> provinceMap = new HashMap<>();
                    for (Map<String, List<List<String>>> map : hosStrList) {
                        Iterator<Map.Entry<String, List<List<String>>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<List<String>>> next = iterator.next();
                            String key = next.getKey();
                            List<List<String>> value = next.getValue();
                            int size = value.size();
                            String province = key.split("_")[0];
                            if (provinceMap.containsKey(province)) {
                                Integer count = provinceMap.get(province);
                                count += value.size();
                                provinceMap.put(province, count);
                            } else {
                                provinceMap.put(province, size);
                            }


                            for (int i = 0; i < size; i++) {
                                table.createRow();
                            }
                            tempIndex = startIndex;
                            List<XWPFTableRow> rows = table.getRows();
                            for (int i = 1; i <= size; i++) {
                                XWPFTableRow newRow = table.getRow(startIndex);
                                List<XWPFTableCell> cells = newRow.getTableCells();
                                for (int j = 0; j < cells.size(); j++) {
                                    XWPFTableCell cell = cells.get(j);
                                    List<String> strList = value.get(i - 1);
                                    for (; t < strList.size(); t++) {
                                        center(cell);
                                        setTable10FontSize(strList.get(t), cell);
                                        t++;
                                        break;
                                    }
                                }
                                t = 0;
                                startIndex++;
                            }
                            //合并单元格
                            mergeCell(tempIndex, rows.size(), table, 2, 1);
                        }
                    }
                    if (provinceMap.values().size() > 0) {
                        AtomicInteger start = new AtomicInteger(1);
                        provinceMap.forEach((k, v) -> {
                            mergeProvinceCell(start.get(), (start.get() - 1) + (v), table, 1, 0);
                            start.set(v + 1);
                        });
                    }
                }
            }
        }
    }

    //单元格写入图片
    private void setCellImage(XWPFTableCell cell, String urls) {
        if (StringUtils.isBlank(urls)) {
            return;
        }
        String[] urlArray = urls.split(",");
        //String ctxPath=ResourceUtil.getConfigByName("webUploadpath");
        List<XWPFParagraph> paragraphs = cell.getParagraphs();
        XWPFParagraph newPara = paragraphs.get(0);
        XWPFRun imageCellRunn = newPara.createRun();
        for (String url : urlArray) {
            //String downLoadPath = ctxPath+File.separator + url;
            File image = new File(url);
            if (!image.exists()) {
                continue;
            }
            int format;
            if (url.endsWith(".emf")) {
                format = XWPFDocument.PICTURE_TYPE_EMF;
            } else if (url.endsWith(".wmf")) {
                format = XWPFDocument.PICTURE_TYPE_WMF;
            } else if (url.endsWith(".pict")) {
                format = XWPFDocument.PICTURE_TYPE_PICT;
            } else if (url.endsWith(".jpeg") || url.endsWith(".jpg")) {
                format = XWPFDocument.PICTURE_TYPE_JPEG;
            } else if (url.endsWith(".png")) {
                format = XWPFDocument.PICTURE_TYPE_PNG;
            } else if (url.endsWith(".dib")) {
                format = XWPFDocument.PICTURE_TYPE_DIB;
            } else if (url.endsWith(".gif")) {
                format = XWPFDocument.PICTURE_TYPE_GIF;
            } else if (url.endsWith(".tiff")) {
                format = XWPFDocument.PICTURE_TYPE_TIFF;
            } else if (url.endsWith(".eps")) {
                format = XWPFDocument.PICTURE_TYPE_EPS;
            } else if (url.endsWith(".bmp")) {
                format = XWPFDocument.PICTURE_TYPE_BMP;
            } else if (url.endsWith(".wpg")) {
                format = XWPFDocument.PICTURE_TYPE_WPG;
            } else {
                continue;
            }
            try (FileInputStream is = new FileInputStream(url)) {
                imageCellRunn.addPicture(is, format, image.getName(), Units.toEMU(100), Units.toEMU(100)); // 200x200 pixels
            } catch (Exception e) {
                e.printStackTrace();
            }
//            imageCellRunn.addBreak();
        }
    }

    private void mergeProvinceCell(int fromIndex, int rowSize, XWPFTable table, int cellSize, int from) {
        for (int rowIndex = fromIndex; rowIndex <= rowSize; rowIndex++) {
            for (int zz = from; zz < cellSize; zz++) {
                XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(zz);
                if (mergeCell1 != null) {
                    if (rowIndex == fromIndex) {
                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                    } else {
                        mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                    }
                    center(mergeCell1);
                }
            }
        }
    }

    private void mergeCell(int tempIndex, int rowSize, XWPFTable table, int cellSize, int from) {
        if (cellSize > 0) {
            for (int rowIndex = tempIndex; rowIndex < rowSize; rowIndex++) {
                for (int zz = from; zz < cellSize; zz++) {
                    XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(zz);
                    if (mergeCell1 != null) {
                        if (rowIndex == tempIndex) {
                            mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                        } else {
                            mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                        }
                        center(mergeCell1);
                    }
                }
            }
        }
    }

    private void setTable10FontSize(String s, XWPFTableCell cell) {
        //设置字体大小
        if (StringUtils.isNotBlank(s)) {
            if (s.contains("\r\n")) {
                for (String text : s.split("\r\n")) {
                    XWPFRun run = getLeftRun(cell);
                    run.setFontSize(11);
                    run.setText(text);
                    run.addBreak();
                }
            } else {
                XWPFRun run = getRun(cell);
                run.setFontSize(11);
                run.setText(s);
            }
        }
    }

    private void setTableFontSize1(String s, XWPFTableCell cell) {
        if (PlatformObjectUtils.isNotEmpty(s) && s.contains("\r\n")) {
            for (String text : s.split("\r\n")) {
                XWPFRun run = getLeftRun(cell);
                run.setFontSize(13);
                run.setText(text);
                run.addBreak();
            }
        } else {
            XWPFRun run = getRun(cell);
            run.setFontSize(13);
            run.setText(PlatformObjectUtils.isNotEmpty(s) ? s : "");
        }
    }

    private void setTableFontSize(String s, XWPFTableCell cell) {
        //设置字体大小
        if (StringUtils.isNotBlank(s)) {
            if (s.contains("\r\n")) {
                for (String text : s.split("\r\n")) {
                    XWPFRun run = getLeftRun(cell);
                    run.setFontSize(13);
                    run.setText(text);
                    run.addBreak();
                }
            } else {
                XWPFRun run = getRun(cell);
                run.setFontSize(13);
                run.setText(s);
            }
        }
    }

    private void setTableHeadFontSize(String s, XWPFTableCell cell) {
        //设置字体大小
        XWPFRun run = getRun(cell);
        run.setFontSize(17);
        run.setText(s);
        run.setBold(true);
    }

    private XWPFRun getRun(XWPFTableCell cell) {
        //获取 CTP
        CTTc ctTc = cell.getCTTc();
        CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
        XWPFParagraph par = cell.getParagraph(ctP);
        XWPFRun run = par.createRun();
        return run;
    }

    private XWPFRun getLeftRun(XWPFTableCell cell) {
        //获取 CTP
        CTTc ctTc = cell.getCTTc();
        CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
        XWPFParagraph par = cell.getParagraph(ctP);
        par.setAlignment(ParagraphAlignment.LEFT);
        XWPFRun run = par.createRun();
        return run;
    }

    private void setTableColumnWidths(XWPFTable table) {
        table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2000));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(3200));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1000));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1000));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1105));
        table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(1105));

    }

    private void createTable(CustomXWPFDocument doc, Map<String, Object> params) {
        Map<String, List<List<String>>> prefectureResultEntityMap = (Map<String, List<List<String>>>) params.get("prefectureResultEntityList");
        Map<String, List<List<String>>> resultEntityMap = (Map<String, List<List<String>>>) params.get("resultEntityList");
        List<XWPFTable> tables = doc.getTables();
        for (int ii = 0; ii < tables.size(); ii++) {
            if (ii == 0) {
                XWPFTable table = tables.get(ii);
                setTableColumnWidths(table);
                int k = 0;
                //记录初始下标
                int startIndex = 1;

                int z = 1;

                Iterator<Map.Entry<String, List<List<String>>>> iterator = prefectureResultEntityMap.entrySet().iterator();
                String area = "";
                AtomicInteger integer = new AtomicInteger(0);
                while (iterator.hasNext()) {
                    Map.Entry<String, List<List<String>>> next = iterator.next();
                    String key = next.getKey();
                    if ("".equals(area)) {
                        area = key.split("_")[0];
                    }
                    if (area.equals(key.split("_")[0])) {
                        integer.getAndIncrement();
                    }
                    if (!area.equals(key.split("_")[0])) {
                        //合并单元格
                        for (int rowIndex = startIndex; rowIndex < (startIndex + integer.get()); rowIndex++) {
                            XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(0);
                            if (mergeCell1 != null) {
                                if (rowIndex == startIndex) {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                } else {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                }
                                center(mergeCell1);
                            }
                        }
                        startIndex = startIndex + integer.get();
                        integer = new AtomicInteger(1);
                        area = key.split("_")[0];
                    }
                    List<List<String>> value = next.getValue();
                    for (int y = 0; y < value.size(); y++) {
                        table.createRow();
                    }
                    List<XWPFTableRow> rows = table.getRows();

                    for (int index = 0; index < next.getValue().size(); index++) {
                        XWPFTableRow newRow = table.getRow(z);
                        //copyStyle(newRow, header);
                        List<XWPFTableCell> cells = newRow.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            center(cell);
                            try {
                                cell.setText(value.get(index).get(j));
                            } catch (IndexOutOfBoundsException e) {
                                e.printStackTrace();
                            }
                        }
                        z++;
                    }
                }
                //最后一个区县/地市合并单元格
                for (int rowIndex = startIndex; rowIndex < (startIndex + integer.get()); rowIndex++) {
                    XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(0);
                    if (mergeCell1 != null) {
                        if (rowIndex == startIndex) {
                            mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                        } else {
                            mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                        }
                        center(mergeCell1);
                    }
                }
                startIndex = 1;
                integer = new AtomicInteger(1);
                area = "";
            } else if (ii == 1) {
                int dbj = 1;
                XWPFTable table = tables.get(ii);
                int k = 0;
                int t = 0;
                //记录初始下标
                int startIndex = 2;
                int tempIndex = 1;
                Iterator<Map.Entry<String, List<List<String>>>> iterator = resultEntityMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, List<List<String>>> next = iterator.next();
                    String key = next.getKey();
                    List<List<String>> value = next.getValue();
                    int size = value.size();
                    for (int i = 0; i < size; i++) {
                        table.createRow();
                    }
                    tempIndex = startIndex;
                    List<XWPFTableRow> rows = table.getRows();
                    for (int i = 2; i <= (size + 1); i++) {
                        XWPFTableRow newRow = table.getRow(startIndex);
                        //copyStyle(newRow, header);
                        List<XWPFTableCell> cells = newRow.getTableCells();
                        for (int j = 0; j < cells.size(); j++) {
                            XWPFTableCell cell = cells.get(j);
                            center(cell);
                            List<String> strList = value.get(i - 2);
                            cell.setText(strList.get(j));
                        }
                        startIndex++;
                    }
                    //合并单元格
                    for (int rowIndex = tempIndex; rowIndex < rows.size(); rowIndex++) {
                        for (int j = 0; j < 4; j++) {
                            XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                            if (mergeCell1 != null) {
                                if (rowIndex == tempIndex) {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                                } else {
                                    mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                                }
                                center(mergeCell1);
                            }
                        }

                    }
                }
                //合并表头 行合并
                for (int rowIndex = 0; rowIndex < 2; rowIndex++) {
                    for (int j = 0; j < 8; j++) {
                        XWPFTableCell mergeCell1 = table.getRow(rowIndex).getCell(j);
                        if (mergeCell1 != null) {
                            if (rowIndex == 0) {
                                mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
                            } else {
                                mergeCell1.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
                            }
                            center(mergeCell1);
                        }
                    }

                }
                //合并表头 列合并
                for (int cellIndex = 8; cellIndex <= 12; cellIndex++) {
                    XWPFTableCell cell = table.getRow(0).getCell(cellIndex);
                    if (cellIndex == 8) {
                        // The first merged cell is set with RESTART merge value
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    } else {
                        // Cells which join (merge) the first one, are set with CONTINUE
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    }
                    center(cell);
                }
            }

        }
    }

    private void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        //center是为了给标题加粗
        int center = 0;
        while (iterator.hasNext()) {
            para = iterator.next();
            para.setWordWrapped(true);
            //行间距
            //para.setSpacingBefore(100);
            center = this.replaceInPara(para, params, doc, center);
        }
    }

    private void replaceInPara1(CustomXWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        //center是为了给标题加粗
        int center = 0;
        while (iterator.hasNext()) {
            para = iterator.next();
            para.setWordWrapped(true);
            //行间距
            //para.setSpacingBefore(100);
            center = this.replaceInPara1(para, params, doc, center);
        }
    }

    private int replaceInPara1(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc, int center) {
        List<XWPFRun> runs;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int temp = 0;
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                int fontSize = run.getFontSize();
                String fontFamily = run.getFontFamily();
                String runText = run.toString().trim();
                if ("".equals(runText)) {
                    continue;
                }
                if ("0}".equals(runText)) {
                    para.removeRun(i);
                    continue;
                }
                if (runText.contains("{") && !runText.contains("}") && runText.length() > 1) {
                    runText = runText + "}";
                }
                if ("{".equals(runText)) {
                    temp = 1;
                }

                if (temp == 1) {
                    if (!"{".equals(runText) && !"}".equals(runText)) {
                        runText = "{" + runText + "}";
                        temp = 0;
                    }
                }
                boolean contains = runText.contains("{");
                if (!runText.contains("{") && !runText.contains("}")) {
                    continue;
                }
                //获取{}中的值
                int firstIndex = runText.indexOf("{");
                int endIndex = runText.indexOf("}");
                int lastIndex = runText.lastIndexOf("}");
                if (firstIndex != -1 && firstIndex + 1 == endIndex) {
                    continue;
                }
                if (endIndex != lastIndex) {
                    //表示存在多个{}
                    //分别获取每一个{}中的值runText
                    List<String> keys = getEveryKey(runText);
                    if (PlatformObjectUtils.isNotEmpty(keys)) {
                        for (String key : keys) {
                            Object o = params.get(key);
                            if (PlatformObjectUtils.isEmpty(o)) {
                                runText = runText.replace("{" + key + "}", "");
                            } else {
                                runText = runText.replace("{" + key + "}", o.toString());
                            }

                        }
                        para.removeRun(i);
                        XWPFRun xwpfRun = para.insertNewRun(i);
                        xwpfRun.setFontSize(fontSize == 22 ? fontSize : 12);
                        xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                        xwpfRun.setText(runText);
                        break;
                    }
                } else {
                    if (firstIndex > -1 || endIndex > -1) {
                        if (runText.startsWith("{image-")) {
                            runText = runText.replace("{", "").replace("}", "");
                            String[] split = runText.split("-");
                            if (StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
                                try {
                                    String imgurl = String.valueOf(params.get(split[1]));
                                    String picType = null;
                                    if (imgurl.contains(".")) {
                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                    }
                                    InputStream inputStream = new FileInputStream(imgurl);
                                    int width = Units.toEMU(Double.parseDouble("450"));
                                    int height = Units.toEMU(Double.parseDouble("350"));
                                    //para.removeRun(i);
                                    run.setText("", 0);
                                    run.addPicture(inputStream, getPictureType(picType), "", width, height);


                                } catch (IOException | InvalidFormatException e) {

                                }
                            }
//                            if (split.length == 2 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
//                                try {
//                                    String imgurl = String.valueOf(params.get(split[1]));
//                                    String picType = null;
//                                    if (imgurl.contains(".")) {
//                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
//                                    }
//                                    InputStream inputStream = new FileInputStream(imgurl);
//                                    int width = Units.toEMU(Double.parseDouble("420"));
//                                    int height = Units.toEMU(Double.parseDouble("240"));
//                                    //para.removeRun(i);
//                                    run.setText("", 0);
//                                    run.addPicture(inputStream, getPictureType(picType), "", width, height);
//                                } catch (IOException | InvalidFormatException e) {
//
//                                }
//                            }else if (split.length == 4 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
//                                try {
//                                    String imgurl = String.valueOf(params.get(split[1]));
//                                    String picType = null;
//                                    if (imgurl.contains(".")) {
//                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
//                                    }
//                                    InputStream inputStream = new FileInputStream(imgurl);
//                                    int width = Units.toEMU(Double.parseDouble(split[2]));
//                                    String widthNum = split[3].length()==3?split[3]:split[3]+0;
//                                    int height = Units.toEMU(Double.parseDouble(widthNum));
//                                    //para.removeRun(i);
//                                    run.setText("", 0);
//                                    run.addPicture(inputStream, getPictureType(picType), "", width, height);
//                                } catch (IOException | InvalidFormatException e) {
//
//                                }
//                            }
                        } else {
                            center++;
                            if ("{".equals(runText) || "}".equals(runText)) {
                                runText = "";
                            } else {
                                String key = runText.substring(firstIndex + 1, endIndex);
                                Object o = params.get(key);
                                if (PlatformObjectUtils.isEmpty(o) || "".equals(o)) {
                                    runText = runText.replace("{" + key + "}", "");
                                } else {
                                    runText = runText.replace("{" + key + "}", o.toString());
                                }
                            }
                            para.removeRun(i);
                            XWPFRun xwpfRun = para.insertNewRun(i);
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily(fontFamily);
                            if (center == 1 || center == 2) {
                                xwpfRun.setBold(true);
                            }
                            xwpfRun.setText(runText);
                        }
                        //break;
                    }
                }

            }
        }
        return center;
    }

    private int replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc, int center) {
        List<XWPFRun> runs;
        if (this.matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int temp = 0;
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                int fontSize = run.getFontSize();
                String fontFamily = run.getFontFamily();
                String runText = run.toString().trim();
                if ("".equals(runText)) {
                    continue;
                }
                if ("0}".equals(runText)) {
                    para.removeRun(i);
                    continue;
                }
                if (runText.contains("{") && !runText.contains("}") && runText.length() > 1) {
                    runText = runText + "}";
                }
                if ("{".equals(runText)) {
                    temp = 1;
                }

                if (temp == 1) {
                    if (!"{".equals(runText) && !"}".equals(runText)) {
                        runText = "{" + runText + "}";
                        temp = 0;
                    }
                }
                boolean contains = runText.contains("{");
                if (!runText.contains("{") && !runText.contains("}")) {
                    continue;
                }
                //获取{}中的值
                int firstIndex = runText.indexOf("{");
                int endIndex = runText.indexOf("}");
                int lastIndex = runText.lastIndexOf("}");
                if (firstIndex != -1 && firstIndex + 1 == endIndex) {
                    continue;
                }
                if (endIndex != lastIndex) {
                    //表示存在多个{}
                    //分别获取每一个{}中的值runText
                    List<String> keys = getEveryKey(runText);
                    if (PlatformObjectUtils.isNotEmpty(keys)) {
                        for (String key : keys) {
                            Object o = params.get(key);
                            if (PlatformObjectUtils.isEmpty(o)) {
                                runText = runText.replace("{" + key + "}", "");
                            } else {
                                runText = runText.replace("{" + key + "}", o.toString());
                            }

                        }
                        para.removeRun(i);
                        XWPFRun xwpfRun = para.insertNewRun(i);
                        xwpfRun.setFontSize(fontSize == 22 ? fontSize : 12);
                        xwpfRun.setFontFamily("".equals(fontFamily) ? "Times New Roman" : fontFamily);
                        xwpfRun.setText(runText);
                        break;
                    }
                } else {
                    if (firstIndex > -1 || endIndex > -1) {
                        if (runText.startsWith("{image-")) {
                            runText = runText.replace("{", "").replace("}", "");
                            String[] split = runText.split("-");
                            if (StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
                                try {
                                    String imgurl = String.valueOf(params.get(split[1]));
                                    String picType = null;
                                    if (imgurl.contains(".")) {
                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
                                    }
                                    InputStream inputStream = new FileInputStream(imgurl);
                                    if (split.length >= 3) {
                                        int width = Units.toEMU(Double.parseDouble("350"));
                                        int height = Units.toEMU(Double.parseDouble("200"));
                                        //para.removeRun(i);
                                        run.setText("", 0);
                                        run.addPicture(inputStream, getPictureType(picType), "", width, height);
                                    } else {
                                        int width = Units.toEMU(Double.parseDouble("620"));
                                        int height = Units.toEMU(Double.parseDouble("490"));
                                        //para.removeRun(i);
                                        run.setText("", 0);
                                        run.addPicture(inputStream, getPictureType(picType), "", width, height);
                                    }

                                } catch (IOException | InvalidFormatException e) {

                                }
                            }
//                            if (split.length == 2 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
//                                try {
//                                    String imgurl = String.valueOf(params.get(split[1]));
//                                    String picType = null;
//                                    if (imgurl.contains(".")) {
//                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
//                                    }
//                                    InputStream inputStream = new FileInputStream(imgurl);
//                                    int width = Units.toEMU(Double.parseDouble("420"));
//                                    int height = Units.toEMU(Double.parseDouble("240"));
//                                    //para.removeRun(i);
//                                    run.setText("", 0);
//                                    run.addPicture(inputStream, getPictureType(picType), "", width, height);
//                                } catch (IOException | InvalidFormatException e) {
//
//                                }
//                            }else if (split.length == 4 && StringUtils.isNotBlank(split[1]) && params.containsKey(split[1])) {
//                                try {
//                                    String imgurl = String.valueOf(params.get(split[1]));
//                                    String picType = null;
//                                    if (imgurl.contains(".")) {
//                                        picType = imgurl.substring(imgurl.lastIndexOf(".") + 1);
//                                    }
//                                    InputStream inputStream = new FileInputStream(imgurl);
//                                    int width = Units.toEMU(Double.parseDouble(split[2]));
//                                    String widthNum = split[3].length()==3?split[3]:split[3]+0;
//                                    int height = Units.toEMU(Double.parseDouble(widthNum));
//                                    //para.removeRun(i);
//                                    run.setText("", 0);
//                                    run.addPicture(inputStream, getPictureType(picType), "", width, height);
//                                } catch (IOException | InvalidFormatException e) {
//
//                                }
//                            }
                        } else {
                            center++;
                            if ("{".equals(runText) || "}".equals(runText)) {
                                runText = "";
                            } else {
                                String key = runText.substring(firstIndex + 1, endIndex);
                                Object o = params.get(key);
                                if (PlatformObjectUtils.isEmpty(o) || "".equals(o)) {
                                    runText = runText.replace("{" + key + "}", "");
                                } else {
                                    runText = runText.replace("{" + key + "}", o.toString());
                                }
                            }
                            para.removeRun(i);
                            XWPFRun xwpfRun = para.insertNewRun(i);
                            xwpfRun.setFontSize(fontSize);
                            xwpfRun.setFontFamily(fontFamily);
                            if (center == 1 || center == 2) {
                                xwpfRun.setBold(true);
                            }
                            xwpfRun.setText(runText);
                        }
                        //break;
                    }
                }

            }
        }
        return center;
    }

    private static int getPictureType(String picType) {
        int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if ("png".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_PNG;
            } else if ("dib".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_DIB;
            } else if ("emf".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_EMF;
            } else if ("jpg".equalsIgnoreCase(picType) || "jpeg".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
            } else if ("wmf".equalsIgnoreCase(picType)) {
                res = CustomXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    private List<String> getEveryKey(String runText) {
        List<Integer> list = new ArrayList<>();
        List<String> keyList = new ArrayList<>();
        char[] chars = runText.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '{') {
                list.add(++i);
            }
            if (chars[i] == '}') {
                list.add(i);
            }
        }
        StringBuilder key = new StringBuilder("");
        for (int i = 0; i < list.size(); i++) {
            key.append(runText.substring(list.get(i), list.get(++i)));
            keyList.add(key.toString());
            key = new StringBuilder("");
        }

        return keyList;
    }

    private Map<String, List<List<String>>> getMainResultList(List<ResultMainEntity> resultMainEntities, List<ResultEntity> resultEntities) {
        Map<String, List<List<String>>> resultMap = new LinkedHashMap<>();
        List<String> strList = new ArrayList<>();
        if (resultMainEntities != null) {
            for (ResultMainEntity entity : resultMainEntities) {
                String longitude = entity.getLongitude();
                String latitude = entity.getLatitude();
                String macroPosition = entity.getMacroPosition();
                String llm = (longitude + "_" + latitude + "_" + macroPosition);
                strList = reportHandle.buildStrList(entity);
                if (resultMap.containsKey(llm)) {
                    List<List<String>> list = resultMap.get(llm);
                    list.add(strList);
                    resultMap.put(llm, list);
                } else {
                    List<List<String>> list = new ArrayList<>();
                    list.add(strList);
                    resultMap.put(llm, list);
                }
            }
        }
        if (resultEntities != null) {
            for (ResultEntity entity : resultEntities) {
                String longitude = entity.getLongitude();
                String latitude = entity.getLatitude();
                String macroPosition = entity.getMacroPosition();
                String llm = (longitude + "_" + latitude + "_" + macroPosition);
                strList = reportHandle.buildStrList(entity);
                if (resultMap.containsKey(llm)) {
                    List<List<String>> list = resultMap.get(llm);
                    list.add(strList);
                    resultMap.put(llm, list);
                } else {
                    List<List<String>> list = new ArrayList<>();
                    list.add(strList);
                    resultMap.put(llm, list);
                }
            }
        }
        return resultMap;
    }

    public void buildYpgResultTable(String dataSource, String taskId, String level, Map<String, Object> dataMap, String taskCode) throws IllegalAccessException {
        Map<String, List<List<String>>> prefectureResultEntityList = new HashMap<>();
        //2使用的是系统手动计算得到的数据
        if ("2".equals(dataSource)) {
            //查询生成的地震的个数
            List<SettingSeismicPoint> settingSeismicPointByTaskId = settingSeismicRepository.getSettingSeismicPointByTaskId(taskId);
            if (PlatformObjectUtils.isNotEmpty(settingSeismicPointByTaskId)) {
                dataMap.put("amount", settingSeismicPointByTaskId.size() + "");
            } else {
                dataMap.put("amount", "0");
            }
            //1地市 2区县 只区分预评估结果表
            if ("1".equals(level)) {
                List<ResultMainEntityVO> cityResultEntityList = resultTotalRepository.getResultTotalForReportByTaskId(taskId);
                if (PlatformObjectUtils.isNotEmpty(cityResultEntityList)) {
                    prefectureResultEntityList = getCityResultList(cityResultEntityList, null);
                }
                //地市级行政区预评估结果统计表
                dataMap.put("prefectureResultEntityList", prefectureResultEntityList);
            } else {
                List<ResultMainEntityVO> resultEntityList = resultTotalRepository.getResultTotalVOByTaskId(taskId);
                if (PlatformObjectUtils.isNotEmpty(resultEntityList)) {
                    prefectureResultEntityList = getCountyResultList(resultEntityList);
                }
                //区县行政区预评估结果统计表
                dataMap.put("prefectureResultEntityList", prefectureResultEntityList);
            }
            List<ResultMainEntity> mainEntities = resultTotalRepository.getResultTotalForReportMainByTaskId(taskId);
            for (ResultMainEntity vo : mainEntities) {
                vo.setLatitude(new BigDecimal(vo.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                vo.setLongitude(new BigDecimal(vo.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            Map<String, List<List<String>>> mainMap = new HashMap<>();
            if (PlatformObjectUtils.isNotEmpty(mainEntities)) {
                //.预评估结果表
                mainMap = getMainResultList(mainEntities, null);
            }
            //生成的是区县单位的数据 用于底部的大表
            dataMap.put("resultEntityList", mainMap);
        } else if ("1".equals(dataSource)) {
            //用户上传的
            //地震个数
            Integer num = resultRepository.prefectureResultCount(taskCode);
            if (PlatformObjectUtils.isEmpty(num)) {
                throw new RuntimeException("查询不到地震信息");
            }
            //地震的个数
            String amount = String.valueOf(num);
            dataMap.put("amount", amount);
            //1使用的是预评估结果上传的数据 两张表展示的是用户上传什么数据就展示什么数据，没有区县之说
            List<PrefectureResultEntity> prefectureList = resultRepository.getPrefectureResult(taskCode);
            if (PlatformObjectUtils.isNotEmpty(prefectureList)) {
                prefectureResultEntityList = getCityResultList(null, prefectureList);
            }
            dataMap.put("prefectureResultEntityList", prefectureResultEntityList);
            //.预评估结果表
            List<ResultEntity> resultEntityList = resultRepository.getResultByTaskId(taskId);
            for (ResultEntity vo : resultEntityList) {
                vo.setLatitude(new BigDecimal(vo.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                vo.setLongitude(new BigDecimal(vo.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
            }
            Map<String, List<List<String>>> mainMap = new HashMap<>();
            if (PlatformObjectUtils.isNotEmpty(resultEntityList)) {
                mainMap = getMainResultList(null, resultEntityList);
            }
            dataMap.put("resultEntityList", mainMap);
        }
    }

    private Map getReportData(PreAssessTaskEntity preAssessTaskEntity, String dataSource, String level, String simplifiedReportTemplate) throws IllegalAccessException {
        Map<String, Object> dataMap = new HashMap<>();
        String taskCode = preAssessTaskEntity.getTaskNum();
        //年度、名称
        String year = preAssessTaskEntity.getTaskYear();
        String name = preAssessTaskEntity.getTaskName();
        dataMap.put("year", year);
        dataMap.put("name", name);
        //当前时间
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(date);
        dataMap.put("time", time);
        if (simplifiedReportTemplate.contains("版本一")) {
            //人口分布图、经济分布图
            String populationPath = mapManagementService.getPopulationPath(preAssessTaskEntity.getId());
            String economicsPath = mapManagementService.getEconomicsPath(preAssessTaskEntity.getId());
            dataMap.put("populationPath", populationPath == null ? "" : populationPath);
            dataMap.put("economicsPath", economicsPath == null ? "" : economicsPath);
            //历史地震
//            List<HistoricalSeismicData> historicalSeismicDataList = historicalSeismicDataService.judgeHistoricalSeismicData(preAssessTaskEntity.getId());
//            StringBuilder historicalSeismicData = new StringBuilder();
//            if (historicalSeismicDataList.size() > 0) {
//                for (int i = 0; i < historicalSeismicDataList.size(); i++) {
//                    historicalSeismicData = historicalSeismicData.append(historicalSeismicDataList.get(i).getHsdTime() +
//                            historicalSeismicDataList.get(i).getHsdReferencename() +
//                            historicalSeismicDataList.get(i).getHsdSgrade() + "、");
//                }
//                historicalSeismicData.deleteCharAt(historicalSeismicData.length() - 1);
//                historicalSeismicData.append("等");
//            }
//            dataMap.put("historicalSeismicData", historicalSeismicData.toString());
            //构建表格数据
            buildYpgResultTable(dataSource, preAssessTaskEntity.getId(), level, dataMap, taskCode);
            //文字部分
            Map<String, Object> map = suggestionAnalysisService.getDataByTaskNum(taskCode);
            //处理地震应急准备和处置要点数据
            String zhqjfx = getZhqjfxText(map.get("zhqjfx"));
            //地震应急准备和处置要点
            // dataMap.put("dzyjzbhczyd",map.get("zhqjfx"));
            dataMap.put("dzyjzbhczyd", zhqjfx);
            //地震应急准备建议
            String yjzbcz = getYjzbczText(map.get("yjzbcz"));
            dataMap.put("dzyjzbjy", yjzbcz);
            //地震应急处置建议
            String yjczdc = getYjczdcText(map.get("yjczdc"));
            dataMap.put("dzyjczjy", yjczdc);
        } else if (simplifiedReportTemplate.contains("版本二")) {
            Map<String, String> pathMap = mapManagementService.getPathByLabel(preAssessTaskEntity.getId());
            //开始构建简本2版本的图片开始
            String earthquakePath = "";
            String keyDanagerPath = "";
            String secondPath = "";
            String populationPath = "";
            String economyPath = "";
            String landformPath = "";
            String geologyPath = "";
            String trafficPath = "";
            if (pathMap != null) {
                earthquakePath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("6") : "";
                keyDanagerPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("7") : "";
                secondPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("8") : "";
                populationPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("1") : "";
                economyPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("2") : "";
                landformPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("3") : "";
                geologyPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("4") : "";
                trafficPath = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("5") : "";
            }
//            earthquakePath = "D:\\image\\123.png";
//            keyDanagerPath = "D:\\image\\b1ae30220c8593cfbd4b8cea3bd12ca4.jpg";
//            secondPath = "D:\\image\\ytxvknkmrs40531.jpg";
//            populationPath = "D:\\image\\图片1.png";
//            economyPath = "D:\\image\\图片2.png";
//            landformPath = "D:\\image\\图片3.png";
//            geologyPath = "D:\\image\\图片4.png";
//            trafficPath = "D:\\image\\图片5.png";

            dataMap.put("earthquakePath", earthquakePath);
            dataMap.put("keyDanagerPath", keyDanagerPath);
            dataMap.put("secondPath", secondPath);
            dataMap.put("populationPath", populationPath);
            dataMap.put("economyPath", economyPath);
            dataMap.put("landformPath", landformPath);
            dataMap.put("geologyPath", geologyPath);
            dataMap.put("trafficPath", trafficPath);
            //开始构建简本2版本的图片结束
            List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(preAssessTaskEntity.getId());
            List<String> taskIdList = null;
            List<String> taskNumList = null;
            JSONObject subArea = new JSONObject();
            //子任务的区域范围不一定刚好就是父任务的区域范围，可能存在跨省的任务，但是分配子任务时只分了其中某一省的任务
            if (PlatformObjectUtils.isNotEmpty(subTask) && subTask.size() > 0) {
                //表示这是个父任务，存在至少一条子任务
                taskIdList = subTask.stream().map(PreAssessTaskEntity::getId).collect(Collectors.toList());
                taskNumList = subTask.stream().map(PreAssessTaskEntity::getTaskNum).collect(Collectors.toList());
                subArea = getSubArea(taskIdList);
            } else {
                subArea = getSubArea(Arrays.asList(preAssessTaskEntity.getId()));
            }
            List<AreaVO> voList = new ArrayList<>();
            if (subArea != null) {
                Map<String, Map<String, List<String>>> mapMap = (Map<String, Map<String, List<String>>>) subArea.get("mapMap");
                StringBuilder provinceMsg = new StringBuilder("");
                AtomicInteger cityNum = new AtomicInteger(0);
                AtomicInteger countyNum = new AtomicInteger(0);
                if (PlatformObjectUtils.isNotEmpty(mapMap) && mapMap.values().size() > 0) {
                    mapMap.forEach((k, v) -> {
                        provinceMsg.append(k).append("、");
                        v.forEach((k1, v1) -> {
                            cityNum.getAndIncrement();
                            v1.forEach(v11 -> {
                                countyNum.getAndIncrement();
                                AreaVO vo = new AreaVO();
                                vo.setProvince(k);
                                vo.setCity(k1);
                                vo.setCounty(v11);
                                voList.add(vo);
                            });
                        });
                    });
                    dataMap.put("provinceMsg", provinceMsg.substring(0, provinceMsg.length() - 1));
                    dataMap.put("cityNum", cityNum.get());
                    dataMap.put("countyNum", countyNum.get());
                }
            } else {
                dataMap.put("provinceMsg", "");
                dataMap.put("cityNum", 0);
                dataMap.put("countyNum", 0);
            }
            //获取震级详情、震级个数，震组
            List<SettingSeismicDetailsVO> settingSeismicDetailsVOS = new ArrayList<>();
            if (taskIdList != null) {
                //表示存在子任务
                List<SettingSeismicDetailsVO> tempResult = settingSeismicRepository.setEarthquakeCensus(taskIdList);
                if (PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size() > 0) {
                    settingSeismicDetailsVOS.addAll(tempResult);
                }
            } else {
                //父任务
                settingSeismicDetailsVOS = settingSeismicRepository.setEarthquakeCensus(preAssessTaskEntity.getId());
            }
            if (PlatformObjectUtils.isNotEmpty(settingSeismicDetailsVOS) && settingSeismicDetailsVOS.size() > 0) {
                List<BigDecimal> collect = settingSeismicDetailsVOS.stream().map(SettingSeismicDetailsVO::getEarthquakeLevel).distinct().collect(Collectors.toList());
                StringBuilder earthquakeDetail = new StringBuilder("");
                collect.forEach(earthLevel -> {
                    earthquakeDetail.append(earthLevel).append("、");
                });
                String earthquakeLevel = earthquakeDetail.substring(0, earthquakeDetail.length() - 1);
                dataMap.put("earthquakeLevel", earthquakeLevel);
                dataMap.put("levelNum", com.css.fxfzypg.util.StringUtils.convertToChinese(collect.size()));
                dataMap.put("group", settingSeismicDetailsVOS.size() + "");
            } else {
                dataMap.put("earthquakeLevel", "");
                dataMap.put("levelNum", 0);
                dataMap.put("group", "0");
            }
            List<KeyDisaterStatics> keyDisaterStaticsList = new ArrayList<>();
            int totalNum = 0;
            AtomicInteger enterpriseNum = new AtomicInteger(0);
            AtomicInteger gasNum = new AtomicInteger(0);
            AtomicInteger tailNum = new AtomicInteger(0);
            List<StructureType> villageList = new ArrayList<>();
            List<StructureType> townList = new ArrayList<>();
            List<Map<String, List<List<String>>>> analysisAllList = new ArrayList<>();
            List<HosPeo> hosPeoList = new ArrayList<>();
            Map<String, List<List<String>>> resultMainMap = new LinkedHashMap<>();
            if (PlatformObjectUtils.isNotEmpty(voList)) {
                //1、表示使用用户上传的数据
                if ("1".equals(dataSource)) {
                    //获取该任务区域下用户上传的数据
                    List<PrefectureResultEntity> uploadResult = new ArrayList<>();
                    if (PlatformObjectUtils.isNotEmpty(taskNumList) && taskNumList.size() > 0) {
                        List<PrefectureResultEntity> tempResult = resultRepository.getUploadResult(taskNumList);
                        if (PlatformObjectUtils.isNotEmpty(tempResult)) {
                            uploadResult.addAll(tempResult);
                        }
                    } else {
                        uploadResult = resultRepository.getUploadResult(preAssessTaskEntity.getTaskNum());
                    }
                    if (PlatformObjectUtils.isNotEmpty(uploadResult)) {
                        Map<String, List<PrefectureResultEntity>> collect = uploadResult.stream().collect(Collectors.groupingBy(PrefectureResultEntity::getCity));
                        collect.forEach((k, v) -> {
                            List<List<String>> strings = new ArrayList<>();
                            //k是city，v是上传的该city下的不同震级的数据
                            v.forEach(prefectureResultEntity -> {
                                prefectureResultEntity.setImportantArea(prefectureResultEntity.getCity());
                                List<String> ceilStrings = reportHandle.buildStrList(prefectureResultEntity);
                                strings.add(ceilStrings);
                            });
                            resultMainMap.put(k, strings);
                        });
                    }
                    //简本二、表1.1地市级行政区预评估结果统计表数据
                    dataMap.put("prefectureResultEntityList", resultMainMap);
                } else if ("2".equals(dataSource)) {
                    //2、表示系统计算的数据
                    //1地市 2区县
                    Map<String, List<List<String>>> finalResultMainMap = resultMainMap;
                    if ("1".equals(level)) {
                        List<String> collect = voList.stream().map(areaVO -> {
                            return areaVO.getProvince() + "-" + areaVO.getCity();
                        }).distinct().collect(Collectors.toList());
                        //主要用于简本版本二第一章表的重点区域（区县）的设置获取地市下的区县且这些区县都在任务区域中
                        Map<String, List<String>> countyMap = new HashMap<>();
                        voList.forEach(vo -> {
                            if (countyMap.containsKey(vo.getProvince() + "_" + vo.getCity())) {
                                List<String> countyNameList = countyMap.get(vo.getProvince() + "_" + vo.getCity());
                                countyNameList.add(vo.getCounty());
                                countyMap.put(vo.getProvince() + "_" + vo.getCity(), countyNameList);
                            } else {
                                List<String> countyNameList = new ArrayList<>();
                                countyNameList.add(vo.getCounty());
                                countyMap.put(vo.getProvince() + "_" + vo.getCity(), countyNameList);
                            }
                        });
                        List<String> finalTaskIdList = taskIdList;
                        collect.forEach(str -> {
                            //以市为单位查询数据
                            List<ResultMainEntityVO> cityResultEntityList = new ArrayList<>();
                            if (PlatformObjectUtils.isNotEmpty(finalTaskIdList) && finalTaskIdList.size() > 0) {
                                List<ResultMainEntityVO> tempResult = resultTotalRepository.getResultTotalForReport(finalTaskIdList, str.split("-")[0], str.split("-")[1]);
                                if (PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size() > 0) {
                                    cityResultEntityList.addAll(tempResult);
                                }
                            } else {
                                cityResultEntityList = resultTotalRepository.getResultTotalForReport(preAssessTaskEntity.getId(), str.split("-")[0], str.split("-")[1]);
                            }

                            String countyStr = "";
                            if (countyMap.values().size() > 0) {
                                List<String> countyNameList = countyMap.get(str.split("-")[0] + "_" + str.split("-")[1]);
                                if (PlatformObjectUtils.isEmpty(countyNameList)) {
                                    countyStr = "没有重点地区";
                                } else {
                                    countyStr = StringUtils.join(countyNameList, ",");
                                }
                            }
                            Map<BigDecimal, ResultMainEntityVO> earthquakeMap = new LinkedHashMap<>();
                            //相同城市相同震级一条数据
                            if (PlatformObjectUtils.isNotEmpty(cityResultEntityList)) {
                                String finalCountyStr = countyStr;
                                cityResultEntityList.forEach(cityResultEntity -> {
                                    //设置地市级的重点地区（区县）
                                    cityResultEntity.setImportantArea(finalCountyStr);
                                    if (earthquakeMap.containsKey(cityResultEntity.getMagnitude())) {
                                        ResultMainEntityVO mainEntityVO = earthquakeMap.get(cityResultEntity.getMagnitude());
                                        try {
                                            //比较并交换特定的字段数据获取字段数据范围数据
                                            reportHandle.compareAndSwap(mainEntityVO, cityResultEntity);
                                            earthquakeMap.put(cityResultEntity.getMagnitude(), mainEntityVO);
                                        } catch (IllegalAccessException e) {
                                            e.printStackTrace();
                                        }
                                    } else {
                                        earthquakeMap.put(cityResultEntity.getMagnitude(), cityResultEntity);
                                    }
                                });
                            }
//                            LinkedHashMap<BigDecimal, ResultMainEntityVO> collectMap = earthquakeMap.entrySet().stream().sorted(Map.Entry.comparingByKey(BigDecimal::compareTo)).
//                                    collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                            if (earthquakeMap.values().size() > 0) {
                                List<List<String>> strings = new ArrayList<>();
                                earthquakeMap.forEach((k, v) -> {
                                    //单位转万人、万顶  （不能在比较并交换的时候转换会出现各种小数点的问题）
                                    reportHandle.handleResult(null, v);
                                    //k是一个震级；v是该震级对应的数据
                                    List<String> ceilDataList = reportHandle.buildStrListV2(v);
                                    strings.add(ceilDataList);
                                });
                                //以市为单位组建数据
                                finalResultMainMap.put(str.split("-")[1], strings);
                            }
                        });
                    } else {
                        //主要用于简本版本二第一章表的区县级的重点区域（调查点）的设置
                        for (AreaVO areaVO : voList) {
                            //以区县为单位查询数据
                            List<ResultMainEntityVO> resultEntityList = new ArrayList<>();
                            if (PlatformObjectUtils.isNotEmpty(taskIdList) && taskIdList.size() > 0) {
                                List<ResultMainEntityVO> tempResult = resultTotalRepository.getResultTotalVO(taskIdList, areaVO.getProvince(), areaVO.getCity(), areaVO.getCounty());
                                if (PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size() > 0) {
                                    resultEntityList.addAll(tempResult);
                                }
                            } else {
                                resultEntityList = resultTotalRepository.getResultTotalVO(preAssessTaskEntity.getId(), areaVO.getProvince(), areaVO.getCity(), areaVO.getCounty());
                            }
                            if (PlatformObjectUtils.isNotEmpty(resultEntityList)) {
                                //查询的是某个区县下的所有的街道信息
                                List<String> streetNameList = new ArrayList<>();
                                List<AreaEntity> streetList = areaRepository.getStreet(areaVO.getProvince(), areaVO.getCity(), areaVO.getCounty());
                                //通过空间数据是否相交判断该街道是否在任务区域总
                                if (PlatformObjectUtils.isNotEmpty(streetList)) {
                                    for (AreaEntity areaEntity : streetList) {
                                        if (reportManagementRepository.getSTIntersects(preAssessTaskEntity.getGeom(), areaEntity.getGeomText())) {
                                            //表示相交
                                            streetNameList.add(areaEntity.getStreet());
                                        }
                                    }
                                }
                                String streetName = "-";
                                ;
                                if (streetNameList.size() > 0) {
                                    streetName = StringUtils.join(streetNameList, ",");
                                }
                                //以区县为单位，相同震级只有一条数据，earthquakeMap有多少个震级就有多少条数据，k为震级，value是某县下的震级对应的数据
                                Map<BigDecimal, ResultMainEntityVO> earthquakeMap = new LinkedHashMap<>();
                                String finalSamplingName = streetName;
                                resultEntityList.forEach(resultMainEntityVO -> {
                                    //设置区县的重点地区抽样调查点
                                    resultMainEntityVO.setImportantArea(finalSamplingName);
                                    resultMainEntityVO.setMacroPosition(resultMainEntityVO.getMacroPosition().split(",")[2]);
                                    //震级
                                    BigDecimal magnitude = resultMainEntityVO.getMagnitude();
                                    if (earthquakeMap.containsKey(magnitude)) {
                                        ResultMainEntityVO mainEntityVO = earthquakeMap.get(magnitude);
                                        try {
                                            //比较并交换特定的字段数据获取字段数据范围数据
                                            reportHandle.compareAndSwap(mainEntityVO, resultMainEntityVO);
                                            earthquakeMap.put(magnitude, mainEntityVO);
                                        } catch (IllegalAccessException e) {
                                            e.printStackTrace();
                                        }
                                    } else {
                                        earthquakeMap.put(magnitude, resultMainEntityVO);
                                    }
                                });
                                LinkedHashMap<BigDecimal, ResultMainEntityVO> collectMap = earthquakeMap.entrySet().stream().sorted(Map.Entry.comparingByKey(BigDecimal::compareTo)).
                                        collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                                if (collectMap.values().size() > 0) {
                                    List<List<String>> strings = new ArrayList<>();
                                    collectMap.forEach((k, v) -> {
                                        //k是一个震级；v是该震级对应的数据
                                        List<String> ceilDataList = buildStrListV3(v);
                                        strings.add(ceilDataList);
                                    });
                                    //以区县为单位组建数据
                                    finalResultMainMap.put(areaVO.getCounty(), strings);
                                }
                            }
                        }
                    }
                    //按key排序
//                    LinkedHashMap<String, List<List<String>>> collectMap = finalResultMainMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
//                            collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                    //简本二、表1.1地市级行政区预评估结果统计表数据
                    dataMap.put("prefectureResultEntityList", finalResultMainMap);
                }
                List<String> dcdList = new ArrayList<>();
                List<BuildingEntity> buildingEntityList = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(subTask) && subTask.size() > 0) {
                    for (PreAssessTaskEntity taskEntity : subTask) {
                        String samplingSurveyPointId = taskEntity.getSamplingSurveyPointId();
                        if (StringUtils.isNotBlank(samplingSurveyPointId)) {
                            String[] idSplit = samplingSurveyPointId.split(",");
                            for (String id : idSplit) {
                                if (!dcdList.contains(id)) {
                                    dcdList.add(id);
                                }
                            }
                        }
                    }
                } else {
                    String samplingSurveyPointId = preAssessTaskEntity.getSamplingSurveyPointId();
                    if (StringUtils.isNotBlank(samplingSurveyPointId)) {
                        String[] idSplit = samplingSurveyPointId.split(",");
                        for (String id : idSplit) {
                            if (!dcdList.contains(id)) {
                                dcdList.add(id);
                            }
                        }
                    }
                }

                if (ObjectUtils.isNotEmpty(dcdList)) {
                    buildingEntityList = buildingReqository.getBuildingSingleData(dcdList);
                }
                for (AreaVO entity : voList) {
                    //表2.1地市级行政区重点隐患风险统计表
                    //化工企业个数
                    Integer riskEnterpriseNum = riskEnterpriseMapService.getAllDataNum(entity.getProvince(), entity.getCity(), entity.getCounty());
                    enterpriseNum.getAndAdd(riskEnterpriseNum == null ? 0 : riskEnterpriseNum);
                    //加油（加气）站个数
                    Integer gasstationNum = gasstationDataMapService.getAllDataNum(entity.getProvince(), entity.getCity(), entity.getCounty());
                    gasNum.getAndAdd(gasstationNum == null ? 0 : gasstationNum);
                    tailNum.getAndAdd(0);
                    //地质灾害隐患（处）
                    Integer geologicalListNum = geologicalMapService.getAllDataNum(entity.getProvince(), entity.getCity(), entity.getCounty());
                    KeyDisaterStatics statics = KeyDisaterStatics.builder().city(entity.getCity()).area(entity.getCounty())
                            .disaterPointNum(String.valueOf(geologicalListNum == null ? 0 : geologicalListNum)).gasNum(String.valueOf(gasstationNum == null ? 0 : gasstationNum)).chemicalNum(String.valueOf(riskEnterpriseNum == null ? 0 : riskEnterpriseNum)).build();
                    keyDisaterStaticsList.add(statics);
                    totalNum += (geologicalListNum == null ? 0 : geologicalListNum);
                    //Gdp
                    GdpEntity gdpEntity = gdpRepositpory.getGdpByDivision(entity.getProvince(), entity.getCity(), entity.getCounty());
                    BigDecimal gdp = (gdpEntity == null || gdpEntity.getGdp() == null) ? new BigDecimal(0) : gdpEntity.getGdp().divide(new BigDecimal(100000000), 4, RoundingMode.HALF_UP);
                    //附表2.评估区城镇建筑物结构类型比例
                    HosPeoEntity hosPeo = hosPeoRepository.findHosPeo(entity.getProvince(), entity.getCity(), entity.getCounty());
                    BigDecimal density = BigDecimal.ZERO;
                    HosPeo hos = new HosPeo();
                    hos.setProvince(entity.getProvince()).setCity(entity.getCity()).setCounty(entity.getCounty());
                    if (PlatformObjectUtils.isNotEmpty(hosPeo)) {
                        if (PlatformObjectUtils.isNotEmpty(hosPeo.getDhpTotalPop()) || PlatformObjectUtils.isNotEmpty(hosPeo.getDhpCountyArea())) {
                            if (hosPeo.getDhpCountyArea().compareTo(BigDecimal.ZERO) != 0) {
                                density = hosPeo.getDhpTotalPop().multiply(new BigDecimal(10000)).divide(hosPeo.getDhpCountyArea(), 0, RoundingMode.DOWN);
                            }
                        }
                        hos.setArea(hosPeo.getDhpCountyArea() == null ? BigDecimal.ZERO : hosPeo.getDhpCountyArea()).
                                setPopulation(hosPeo.getDhpTotalPop() == null ? BigDecimal.ZERO : hosPeo.getDhpTotalPop());
                    } else {
                        hos.setArea(BigDecimal.ZERO).
                                setPopulation(BigDecimal.ZERO);
                    }
                    hos.setDensity(density + "").setGdp(gdp + "");
                    hosPeoList.add(hos);
                    //构建农村和城镇建筑比例
                    if (hosPeo == null) {
                        hosPeo = new HosPeoEntity();
                        //没有数据也要展示基础数据
                        hosPeo.setProvince(entity.getProvince());
                        hosPeo.setCity(entity.getCity());
                        hosPeo.setPrefecture(entity.getCounty());
                    }
                    StructureType village = getVillageRatio(hosPeo);
                    StructureType town = getTownRatio(hosPeo);
                    if (village != null) {
                        villageList.add(village);
                    }
                    if (town != null) {
                        townList.add(town);
                    }
                    //附表4典型建筑物抗震能力分析数据获取和处理
//                    List<BuildingEntityVO> buildingEntityList = null;
//                    if("1".equals(level)){
//                        buildingEntityList =  buildingReqository.queryBuildingEntityData(preAssessTaskEntity.getTaskNum(), entity.getProvince(), entity.getCity(), "");
//                    }else if("2".equals(level)){
//                        buildingEntityList =  buildingReqository.queryBuildingEntityData(preAssessTaskEntity.getTaskNum(), entity.getProvince(), entity.getCity(), entity.getCounty());
//                    }
                }
                if (buildingEntityList.size() > 0) {
                    List<Map<String, List<List<String>>>> analysisList = null;
                    if (PlatformObjectUtils.isNotEmpty(buildingEntityList)) {
                        analysisList = buildSeismicCapacityAnalysis(buildingEntityList, level);
                    }
                    if (analysisList != null) {
                        analysisAllList.addAll(analysisList);
                    }
                }
            }
            dataMap.put("level", level);
            dataMap.put("enterpriseNum", enterpriseNum.get());
            dataMap.put("analysisAllList", analysisAllList);
            Map<String, List<List<String>>> mainMap = new HashMap<>();
            if ("1".equals(dataSource)) {
                //.预评估结果表
                List<ResultEntity> resultEntityList = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(taskIdList) && taskIdList.size() > 0) {
                    List<ResultEntity> tempResult = resultRepository.getResultByTaskId(taskIdList);
                    if (PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size() > 0) {
                        resultEntityList.addAll(tempResult);
                    }
                } else {
                    resultEntityList = resultRepository.getResultByTaskId(preAssessTaskEntity.getId());
                }
                if (PlatformObjectUtils.isNotEmpty(resultEntityList)) {
                    //地市需要换算成万
                    if ("1".equals(level)) {
                        for (ResultEntity resultEntity : resultEntityList) {
                            handleResultEntity(resultEntity);
                            resultEntity.setLatitude(new BigDecimal(resultEntity.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                            resultEntity.setLongitude(new BigDecimal(resultEntity.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                        }
                    }
                    mainMap = getMainResultList1(null, null, resultEntityList);
                }
                dataMap.put("resultEntityList", mainMap);
            } else if ("2".equals(dataSource)) {
                List<ResultMainEntity> mainEntities = new ArrayList<>();
                if (PlatformObjectUtils.isNotEmpty(taskIdList) && taskIdList.size() > 0) {
                    List<ResultMainEntity> tempResult = resultTotalRepository.getResultTotalForReportMainByTaskId(taskIdList);
                    if (PlatformObjectUtils.isNotEmpty(tempResult) && tempResult.size() > 0) {
                        mainEntities.addAll(tempResult);
                    }
                } else {
                    mainEntities = resultTotalRepository.getResultTotalForReportMainByTaskId(preAssessTaskEntity.getId());
                }
                if (PlatformObjectUtils.isNotEmpty(mainEntities)) {
                    //地市需要换算成万
                    if ("1".equals(level)) {
                        mainEntities.forEach(entity -> {
                            handleResultMainEntity(entity);
                        });
                    }
                    //地市级行政区预评估结果统计表
                    //.预评估结果表
                    mainMap = getMainResultList1(null, mainEntities, null);
                }
                //生成的是区县单位的数据 用于底部的大表
                dataMap.put("resultEntityList", mainMap);
            }
            dataMap.put("gasNum", gasNum.get());
            dataMap.put("enterpriseNum", enterpriseNum.get());
            dataMap.put("tailNum", tailNum.get());
//            gasNum.getAndAdd(enterpriseNum.get());
//            tailNum.getAndAdd(gasNum.get());
            dataMap.put("num", totalNum);
            List<Map<String, List<List<String>>>> kdsList = new ArrayList<>();
            //对重点隐患风险统计表数据进行处理
            if (keyDisaterStaticsList.size() > 0) {
                Map<String, List<KeyDisaterStatics>> collect = keyDisaterStaticsList.stream().collect(Collectors.groupingBy(KeyDisaterStatics::getCity));
                collect.forEach((k, v) -> {
                    Map<String, List<List<String>>> kdsMap = new HashMap();
                    List<List<String>> strList = new ArrayList<>(v.size());
                    v.forEach(kds -> {
                        List<String> entityStrList = getEntityStringList(kds);
                        strList.add(entityStrList);
                    });
                    kdsMap.put(k, strList);
                    kdsList.add(kdsMap);
                });
            }
            dataMap.put("keyDisaterStaticsList", kdsList);
            //获取简本版本2中3-1~3-3 表数据并进行加工处理
            Map<String, Object> suggestion = getSuggestion(preAssessTaskEntity, level, voList, new StringBuilder());
            List<Suggestion> suggestionList = (List<Suggestion>) suggestion.get("disasterSuggestList");
            List<AnnualRisk> riskList = (List<AnnualRisk>) suggestion.get("riskList");
            List<Disposal> disposalList = (List<Disposal>) suggestion.get("disposalList");
            List<List<String>> suggestionStrList = new ArrayList<>();
            List<List<String>> riskStrList = new ArrayList<>();
            List<List<String>> disposalStrList = new ArrayList<>();
            if (suggestionList.size() > 0) {
                suggestionList.forEach(entity -> {
                    List<String> entityStrList = new ArrayList<>();
                    entityStrList.add(entity.getAreaName());
                    /** 构建字符串
                     * 1. 建筑物破坏：
                     * 2. 人员伤亡：
                     * 3. 地质灾害：
                     * 4. 次生灾害
                     * 5. 震后交通:
                     * 6. 震后交通:
                     */
                    StringBuilder build = new StringBuilder("");
                    AtomicInteger titleNum = new AtomicInteger(1);
                    if (StringUtils.isNotBlank(entity.getBuildingDamage())) {
                        build.append(titleNum.getAndAdd(1)).append(". 建筑物破坏：").append(entity.getBuildingDamage()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getCasualties())) {
                        build.append(titleNum.getAndAdd(1)).append(". 人员伤亡：").append(entity.getCasualties()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getGeologicHazard())) {
                        build.append(titleNum.getAndAdd(1)).append(". 地质灾害：").append(entity.getGeologicHazard()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getSecondaryDisaster())) {
                        build.append(titleNum.getAndAdd(1)).append(". 次生灾害：").append(entity.getSecondaryDisaster()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getEarthquakeTraffic())) {
                        build.append(titleNum.getAndAdd(1)).append(". 震后交通：").append(entity.getEarthquakeTraffic()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getOtherDisaster())) {
                        build.append(titleNum.getAndAdd(1)).append(". 其他灾害情景：").append(entity.getOtherDisaster());
                    }
                    entityStrList.add(build.toString());
                    suggestionStrList.add(entityStrList);
                });
            }
            dataMap.put("suggestionList", suggestionStrList);
            if (riskList.size() > 0) {
                riskList.forEach(entity -> {
                    List<String> entityStrList = new ArrayList<>();
                    entityStrList.add(entity.getAreaName());
                    StringBuilder build = new StringBuilder("");
                    AtomicInteger titleNum = new AtomicInteger(1);
                    if (StringUtils.isNotBlank(entity.getBuilding())) {
                        build.append(titleNum.getAndAdd(1)).append(". 建筑物：").append(entity.getBuilding()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getDisasterHiddenDanger())) {
                        build.append(titleNum.getAndAdd(1)).append(". 地震灾害重点隐患：").append(entity.getDisasterHiddenDanger()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getLifelineSystem())) {
                        build.append(titleNum.getAndAdd(1)).append(". 生命线系统：").append(entity.getLifelineSystem()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getMajorInfrastructure())) {
                        build.append(titleNum.getAndAdd(1)).append(". 重大基础设施：").append(entity.getMajorInfrastructure()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getOtherAnnualDisaster())) {
                        build.append(titleNum.getAndAdd(1)).append(". 其他年度风险应对策略：").append(entity.getOtherAnnualDisaster());
                    }
                    entityStrList.add(build.toString());
                    riskStrList.add(entityStrList);
                });
            }
            dataMap.put("riskList", riskStrList);
            if (disposalList.size() > 0) {
                disposalList.forEach(entity -> {
                    List<String> entityStrList = new ArrayList<>();
                    entityStrList.add(entity.getAreaName());
                    StringBuilder build = new StringBuilder("");
                    AtomicInteger titleNum = new AtomicInteger(1);
                    if (StringUtils.isNotBlank(entity.getInput())) {
                        build.append(titleNum.getAndAdd(1)).append(". 救援力量和物资投入：").append(entity.getInput()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getCritical())) {
                        build.append(titleNum.getAndAdd(1)).append(". 地震灾害危重区域识别：").append(entity.getCritical()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getTraffic())) {
                        build.append(titleNum.getAndAdd(1)).append(". 交通系统保障和抢修：").append(entity.getTraffic()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getCommunications())) {
                        build.append(titleNum.getAndAdd(1)).append(". 通信系统保障和抢修：").append(entity.getCommunications()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getPower())) {
                        build.append(titleNum.getAndAdd(1)).append(". 电力系统保障和抢修：").append(entity.getPower()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getImportant())) {
                        build.append(titleNum.getAndAdd(1)).append(". 重要基础设施隐患排查：").append(entity.getImportant()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getClimate())) {
                        build.append(titleNum.getAndAdd(1)).append(". 气候特征应对：").append(entity.getClimate()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getNation())) {
                        build.append(titleNum.getAndAdd(1)).append(". 民族特征应对：").append(entity.getNation()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getRumor())) {
                        build.append(titleNum.getAndAdd(1)).append(". 谣言、舆情应对：").append(entity.getRumor()).append("\r\n");
                    }
                    if (StringUtils.isNotBlank(entity.getOther())) {
                        build.append(titleNum.getAndAdd(1)).append(". 其他地方特征应对：").append(entity.getOther()).append("\r\n");
                    }
                    entityStrList.add(build.toString());
                    disposalStrList.add(entityStrList);
                });
            }

            dataMap.put("disposalList", disposalStrList);
            //获取简本版本2中3-1~3-3 表数据并进行加工处理结束
            //获取附表2~3数据并进行处理
            Map<String, List<StructureType>> cityGroupList = null;
            Map<String, List<StructureType>> provinceGroupList = new HashMap<>();
            Map<String, List<StructureType>> villageGroupList = null;
            if (townList.size() > 0) {
                cityGroupList = townList.stream().collect(Collectors.groupingBy(hos -> hos.getProvince() + "_" + hos.getCity()));
                provinceGroupList = townList.stream().collect(Collectors.groupingBy(hos -> hos.getProvince()));
            }
            if (villageList.size() > 0) {
                villageGroupList = villageList.stream().collect(Collectors.groupingBy(hos -> hos.getProvince() + "_" + hos.getCity()));
            }
            List<Map<String, List<List<String>>>> townStructureList = new ArrayList<>();
            if (PlatformObjectUtils.isNotEmpty(cityGroupList) && cityGroupList.size() > 0) {
                cityGroupList.forEach((k1, v1) -> {
                    Map<String, List<List<String>>> collectMap = new HashMap<>();
                    List<List<String>> v1List = new ArrayList<>(v1.size());
                    v1.forEach(obj -> {
                        List<String> entityStrList = getEntityStringList(obj);
                        v1List.add(entityStrList);
                    });
                    collectMap.put(k1, v1List);
                    townStructureList.add(collectMap);
                });
            }
            dataMap.put("townStructureList", townStructureList);
            List<Map<String, List<List<String>>>> villageStructureList = new ArrayList<>();
            if (PlatformObjectUtils.isNotEmpty(villageGroupList) && villageGroupList.size() > 0) {
                villageGroupList.forEach((k1, v1) -> {
                    Map<String, List<List<String>>> collectMap = new HashMap<>();
                    List<List<String>> v1List = new ArrayList<>(v1.size());
                    v1.forEach(obj -> {
                        List<String> entityStrList = getEntityStringList(obj);
                        v1List.add(entityStrList);
                    });
                    collectMap.put(k1, v1List);
                    villageStructureList.add(collectMap);
                });
            }
            dataMap.put("villageStructureList", villageStructureList);
            dataMap.put("provinceGroupList", provinceGroupList);

            //附表3.1  评估区内县级行政区人口和经济数据统计表数据的获取和处理
            Map<String, List<HosPeo>> cityHosList = null;
            Map<String, List<HosPeo>> provincePeoList = new HashMap<>();
            if (hosPeoList.size() > 0) {
                cityHosList = hosPeoList.stream().collect(Collectors.groupingBy(hos -> hos.getProvince() + "_" + hos.getCity()));
                provincePeoList = hosPeoList.stream().collect(Collectors.groupingBy(hos -> hos.getProvince()));
            }
            List<Map<String, List<List<String>>>> hosStrList = new ArrayList<>();
            if (PlatformObjectUtils.isNotEmpty(cityHosList) && cityHosList.size() > 0) {
                cityHosList.forEach((k1, v1) -> {
                    Map<String, List<List<String>>> collectMap = new HashMap<>();
                    List<List<String>> v1List = new ArrayList<>(v1.size());
                    v1.forEach(obj -> {
                        List<String> entityStrList = getEntityStringList(obj);
                        v1List.add(entityStrList);
                    });
                    collectMap.put(k1, v1List);
                    hosStrList.add(collectMap);
                });
            }
            dataMap.put("hosStrList", hosStrList);
            dataMap.put("provincePeoList", provincePeoList);

            //获取历史地震表
            List<HistoricalSeismicData> historicalSeismicData = historicalSeismicDataRepository.getHistoricalSeismicData();
            RoadQueryParams roadQueryParams = new RoadQueryParams();
            AirportQueryParams airQueryParams = new AirportQueryParams();
            //交通情况
            StringBuilder roadBuilder = new StringBuilder();
            //航空情况
            StringBuilder airBuilder = new StringBuilder();
            AtomicInteger historyEarth = new AtomicInteger(0);
            for (AreaVO areaVO : voList) {
                roadQueryParams.setProvince(areaVO.getProvince());
                roadQueryParams.setCity(areaVO.getCity());
                roadQueryParams.setCounty(areaVO.getCounty());
                Map<String, Object> allData = roadMapService.getAllData(roadQueryParams);
                Object total = allData.get("total");
                if (total != null) {
                    Integer num = (Integer) total;
                    if (num > 0) {
                        List<Road> roadList = (List<Road>) allData.get("rows");
                        if (roadList.size() > 0) {
                            List<String> collect = roadList.stream().map(Road::getRoadName).collect(Collectors.toList());
                            String join = StringUtils.join(collect, "、");
                            roadBuilder.append(join);
                        }
                    }
                }
                airQueryParams.setProvince(areaVO.getProvince());
                airQueryParams.setCity(areaVO.getCity());
                airQueryParams.setCounty(areaVO.getCounty());
                Map<String, Object> airPortMap = airportMapService.getAllData(airQueryParams);
                Object airTotal = airPortMap.get("total");
                if (airTotal != null) {
                    Integer num = (Integer) airTotal;
                    if (num > 0) {
                        List<Airport> airList = (List<Airport>) airPortMap.get("rows");
                        if (airList.size() > 0) {
                            List<String> collect = airList.stream().map(Airport::getAirportName).collect(Collectors.toList());
                            String join = StringUtils.join(collect, "、");
                            airBuilder.append(join);
                        }
                    }
                }
                //获取省市县的空间数据
                String codeByCondition = sysAreaService.getCodeByCondition(areaVO.getProvince(), areaVO.getCity(), areaVO.getCounty());
                String countyCode = "";
                if (StringUtils.isNotBlank(codeByCondition) && codeByCondition.split("_").length == 3) {
                    countyCode = codeByCondition.split("_")[2];
                }
                if (StringUtils.isNotBlank(countyCode)) {
                    BoundaryEntity entity = boundaryNativeRepository.getBoundaryEntityByCountyCode(countyCode);
                    if (entity != null) {
                        if (historicalSeismicData != null && historicalSeismicData.size() > 0) {
                            for (HistoricalSeismicData historicalSeismicDatum : historicalSeismicData) {
                                if (boundaryNativeRepository.getSTIntersects(entity.getCoordinate(), historicalSeismicDatum.getHsdLongitude(), historicalSeismicDatum.getHsdLatitude())) {
                                    historyEarth.getAndAdd(1);
                                }
                            }
                        }
                    }
                }
            }
            //历史地震
            dataMap.put("historyMsg", historyEarth + "次地震");
            //公路信息
            dataMap.put("highwayMsg", "".contentEquals(roadBuilder) ? "" : roadBuilder);
            //刚空信息
            dataMap.put("aviationMsg", "".contentEquals(airBuilder) ? "" : airBuilder);
        }

        return dataMap;
    }


    private Map<String, List<List<String>>> getCountyResultList(List<ResultMainEntityVO> resultEntityList) throws IllegalAccessException {
        Map<String, List<List<String>>> tempMap = new HashMap<>();
        if (resultEntityList != null) {
            Map<String, ResultMainEntityVO> resultMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : resultEntityList) {
                //宏观位置
                String macroPosition = mainEntity.getMacroPosition();
                if (StringUtils.isNotBlank(macroPosition)) {
                    mainEntity.setMacroPosition(macroPosition.split(",")[2]);
                    //区县级
                    String country = macroPosition.split(",")[2];
                    //震级
                    BigDecimal magnitude = mainEntity.getMagnitude();
                    if (resultMap.containsKey(country + "_" + magnitude)) {
                        ResultMainEntityVO entity = resultMap.get(country + "_" + magnitude);
                        //compareAndSwap(entity, mainEntity);
                        reportHandle.addData(entity, mainEntity);
                        resultMap.put(country + "_" + magnitude, entity);
                    } else {
                        resultMap.put(country + "_" + magnitude, mainEntity);
                    }
                }
            }

            if (resultMap.values().size() > 0) {
                Iterator<Map.Entry<String, ResultMainEntityVO>> iterator = resultMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, ResultMainEntityVO> next = iterator.next();
                    String county = next.getKey();
                    ResultMainEntityVO value = next.getValue();
                    List<String> strList = reportHandle.buildStrList(value);
                    if (!tempMap.containsKey(county)) {
                        List<List<String>> tempList = new ArrayList<>();
                        tempList.add(strList);
                        tempMap.put(county, tempList);
                    } else {
                        List<List<String>> tempList = tempMap.get(county);
                        tempList.add(strList);
                        tempMap.put(county, tempList);
                    }
                }
            }
        }
        LinkedHashMap<String, List<List<String>>> collectMap = tempMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
        return collectMap;
    }

    public List<Map<String, List<List<String>>>> getCityResultListV3(List<ResultMainEntityVO> cityResultEntityList, List<ResultMainEntityVO> resultEntityList, List<PrefectureResultEntity> prefectureResultEntityList) throws IllegalAccessException {
        List<Map<String, List<List<String>>>> resultList = new ArrayList<>();
        String temp = "";
        if (cityResultEntityList != null) {
            List<Map<String, Map<BigDecimal, ResultMainEntityVO>>> voList = new ArrayList<>();
            Map<String, List<String>> tempMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : cityResultEntityList) {
                String macroPosition = mainEntity.getMacroPosition();
                String[] split = macroPosition.split(",");
                if (split.length >= 3) {
                    if (!tempMap.containsKey(split[1])) {
                        List<String> tempList = new ArrayList<>();
                        tempList.add(split[2]);
                        tempMap.put(split[1], tempList);
                    } else {
                        List<String> tempList = tempMap.get(split[1]);
                        if (!tempList.contains(split[2])) {
                            tempList.add(split[2]);
                            tempMap.put(split[1], tempList);
                        }
                    }
                }
            }
            Map<String, Map<BigDecimal, ResultMainEntityVO>> resultMap = new HashMap<>();
            List<ResultMainEntityVO> voes = new ArrayList<>();
            ResultMainEntityVO tempVO = null;
            for (ResultMainEntityVO entity : cityResultEntityList) {
                //宏观位置
                String macroPosition = entity.getMacroPosition();
                String city = macroPosition.split(",")[1];
                if (tempMap.containsKey(city)) {
                    List<String> tempList = tempMap.get(city);
                    String str = String.join(",", tempList);
                    entity.setImportantArea(str);
                }
                //震级
                BigDecimal magnitude = entity.getMagnitude();
                if (resultMap.containsKey(city)) {
                    Map<BigDecimal, ResultMainEntityVO> voMap = resultMap.get(city);
                    ResultMainEntityVO vo = voMap.get(magnitude);
                    if (vo != null) {
                        // 以地市为单位分别获取相同震级下的最大值和最小值
                        /**
                         * 重庆市,重庆市 5.5 59009-61741 177027-185224
                         * 重庆市,重庆市 6.0 87695-94869 263086-284607
                         * 重庆市,重庆市 6.5 76419-78609 229258-235829
                         */
                        compareAndSwap2(vo, entity);
                        voMap.put(magnitude, vo);
                        resultMap.put(city, voMap);
                    } else {
                        voMap.put(magnitude, entity);
                        resultMap.put(city, voMap);
                    }
                } else {
                    Map<BigDecimal, ResultMainEntityVO> voMap = new HashMap<>();
                    voMap.put(magnitude, entity);
                    resultMap.put(city, voMap);
                }
            }
            if (resultMap.values().size() > 0) {
                voList.add(resultMap);
            }

            if (PlatformObjectUtils.isNotEmpty(voList)) {
                for (Map<String, Map<BigDecimal, ResultMainEntityVO>> voMap : voList) {
                    voMap.forEach((k, v) -> {
                        Map<String, List<List<String>>> map = new HashMap<>();
                        List<List<String>> tempList = new ArrayList<>();
                        Map<BigDecimal, ResultMainEntityVO> tmap = v;
                        Set<Map.Entry<BigDecimal, ResultMainEntityVO>> entries = v.entrySet();
                        Iterator<Map.Entry<BigDecimal, ResultMainEntityVO>> iterator = entries.iterator();
                        while (iterator.hasNext()) {
                            ResultMainEntityVO value = iterator.next().getValue();
                            List<String> strList = buildStrListV2(value);
                            tempList.add(strList);
                        }
                        map.put(k, tempList);
                        resultList.add(map);
                    });
                }

            }
        }
        if (resultEntityList != null) {
            List<Map<String, Map<BigDecimal, ResultMainEntityVO>>> voList = new ArrayList<>();
            Map<String, List<String>> tempMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : resultEntityList) {
                String macroPosition = mainEntity.getMacroPosition();

                String[] split = macroPosition.split(",");
                //if(split.length>=2){
                if (!tempMap.containsKey(split[1] + "," + split[2])) {
                    List<String> tempList = new ArrayList<>();
                    tempList.add(split[1] + "," + split[2]);
                    tempMap.put(split[1] + "," + split[2], tempList);
                } else {
                    List<String> tempList = tempMap.get(split[1] + "," + split[2]);
                    if (!tempList.contains(split[1] + "," + split[2])) {
                        tempList.add(split[1] + "," + split[2]);
                        tempMap.put(split[1] + "," + split[2], tempList);
                    }
                }
                //}
            }
            Map<String, Map<BigDecimal, ResultMainEntityVO>> resultMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : resultEntityList) {
                //宏观位置
                String macroPosition = mainEntity.getMacroPosition();
                mainEntity.setMacroPosition(macroPosition.split(",")[1] + "," + macroPosition.split(",")[2]);
                String city = macroPosition.split(",")[1];
                String country = macroPosition.split(",")[2];
                if (tempMap.containsKey(city + "," + country)) {
                    List<String> tempList = tempMap.get(city + "," + country);
                    String str = String.join(",", tempList);
                    mainEntity.setImportantArea(str);
                }
                //震级
//                BigDecimal magnitude = mainEntity.getMagnitude();
//                if (resultMap.containsKey(country + "_" + magnitude)) {
//                    ResultMainEntityVO entity = resultMap.get(country + "_" + magnitude);
//                    //compareAndSwap(entity, mainEntity);
//                    addData(entity, mainEntity);
//                } else {
////                    if (resultMap.values().size() > 0) {
////                        voList.add(resultMap);
////                        //resultMap = new HashMap<>();
////                    }
//                    resultMap.put(country + "_" + magnitude, mainEntity);
//                }

                BigDecimal magnitude = mainEntity.getMagnitude();
                if (resultMap.containsKey(city + "," + country)) {
                    Map<BigDecimal, ResultMainEntityVO> voMap = resultMap.get(city + "," + country);
                    ResultMainEntityVO vo = voMap.get(magnitude);
                    if (vo != null) {
                        addData(vo, mainEntity);
                        if ("0".equals(vo.getRescueForceAfter())) {
                            vo.setRescueForceAfter("");
                        }
                        if ("0".equals(vo.getTentNumAfter())) {
                            vo.setTentNumAfter("");
                        }
                        voMap.put(magnitude, vo);
                        resultMap.put(city + "," + country, voMap);
                    } else {
                        String resettledNumAfter = mainEntity.getResettledNumAfter();
                        if (!"".equals(resettledNumAfter) && resettledNumAfter != null && !resettledNumAfter.equals("null")) {
                            mainEntity.setResettledNumAfter(divideTenThousand(new BigDecimal(resettledNumAfter)) + "");
                        }
                        String tentNumAfter = mainEntity.getTentNumAfter();
                        if (!"".equals(tentNumAfter) && tentNumAfter != null && !tentNumAfter.equals("null")) {
                            mainEntity.setTentNumAfter(divideTenThousand(new BigDecimal(tentNumAfter)) + "");
                        }
                        voMap.put(magnitude, mainEntity);
                        resultMap.put(city + "," + country, voMap);
                    }
                } else {
                    Map<BigDecimal, ResultMainEntityVO> voMap = new HashMap<>();
                    //紧急安置人数和需要的帐篷，不管是按照区县生成还是地市生成，单位都是万 ，在此处理解决的是只有一条数据，不会存在数据比对的情况
                    String resettledNumAfter = mainEntity.getResettledNumAfter();
                    if (!"".equals(resettledNumAfter) && resettledNumAfter != null && !resettledNumAfter.equals("null")) {
                        mainEntity.setResettledNumAfter(divideTenThousand(new BigDecimal(resettledNumAfter)) + "");
                    }
                    String tentNumAfter = mainEntity.getTentNumAfter();
                    if (!"".equals(tentNumAfter) && tentNumAfter != null && !tentNumAfter.equals("null")) {
                        mainEntity.setTentNumAfter(divideTenThousand(new BigDecimal(tentNumAfter)) + "");
                    }
                    voMap.put(magnitude, mainEntity);
                    resultMap.put(city + "," + country, voMap);
                }
            }
            if (resultMap.values().size() > 0) {
                voList.add(resultMap);
                resultMap = new HashMap<>();
            }
            if (PlatformObjectUtils.isNotEmpty(voList)) {
                for (Map<String, Map<BigDecimal, ResultMainEntityVO>> voMap : voList) {
                    voMap.forEach((k, v) -> {
                        Map<String, List<List<String>>> map = new HashMap<>();
                        List<List<String>> tempList = new ArrayList<>();
                        Map<BigDecimal, ResultMainEntityVO> tmap = v;
                        Set<Map.Entry<BigDecimal, ResultMainEntityVO>> entries = v.entrySet();
                        Iterator<Map.Entry<BigDecimal, ResultMainEntityVO>> iterator = entries.iterator();
                        while (iterator.hasNext()) {
                            ResultMainEntityVO value = iterator.next().getValue();
                            List<String> strList = buildStrListV2(value);
                            tempList.add(strList);
                        }
                        map.put(k, tempList);
                        resultList.add(map);
                    });
                }
            }
        }
        if (prefectureResultEntityList != null) {
            List<List<String>> tempList = new ArrayList<>();
            Map<String, List<List<String>>> map = new HashMap<>();
            List<String> strList = new ArrayList<>();
            for (PrefectureResultEntity entity : prefectureResultEntityList) {
//                String city = entity.getCity();
//                if ("".equals(temp)) {
//                    temp = city;
//                }
//                if (!temp.equals(city)) {
//                    map.put(temp, tempList);
//                    tempList = new ArrayList<>();
//                    resultList.add(map);
//                    map = new HashMap<>();
//                    temp = city;
//                }
                strList = buildStrListV2(entity);
                tempList.add(strList);
            }
            map.put(temp, tempList);
            resultList.add(map);
        }
        return resultList;
    }

    private BigDecimal max(BigDecimal count1, BigDecimal count2) {
        return count1.compareTo(count2) >= 0 ? count1 : count2;
    }

    private BigDecimal min(BigDecimal count1, BigDecimal count2) {
        return count1.compareTo(count2) >= 0 ? count2 : count1;
    }

    /**
     * 当name是紧急安置人数或帐篷时单位转换成万元，否则保持不变
     */
    private String handleData(String name, String value0, String value1) {
        StringBuilder finalValue = new StringBuilder();
        if (name.equals("resettledNumAfter") || name.equals("tentNumAfter")) {
            finalValue.append(divideTenThousand(new BigDecimal(value0)));
            if (!"".equals(value1)) {
                finalValue.append("-").append(divideTenThousand(new BigDecimal(value1)));
            }
        } else {
            finalValue.append(value0);
            if (!"".equals(value1)) {
                finalValue.append("-").append(value1);
            }
        }
        return finalValue.toString();
    }

    private String handleData(String name, BigDecimal double0, BigDecimal double1) {
        StringBuilder finalValue = new StringBuilder();
        if (name.equals("resettledNumAfter") || name.equals("tentNumAfter")) {
            finalValue.append(divideTenThousand(double0)).append("-").append(divideTenThousand(double1));
        } else {
            finalValue.append(double0).append("-").append(double1);
        }
        return finalValue.toString();
    }

    private BigDecimal divideTenThousand(BigDecimal value) {
        return value.divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_DOWN);
    }

    /**
     * 数据单位转换：人转换为万人并保留1位小数
     */
    private void handleResultMainEntity(ResultMainEntity pr) {
        String tent = "";
        String tentNum = pr.getTentNumAfter();
        if (PlatformObjectUtils.isEmpty(tentNum)) {
            pr.setTentNumAfter("");
        } else {
            String[] split = tentNum.split("-");
            BigDecimal prefix = new BigDecimal(split[0]);
            if (split.length == 2) {
                BigDecimal subfix = new BigDecimal(split[1]);
                BigDecimal prefixDivide = prefix.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : prefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                BigDecimal subfixDivide = subfix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                tent = prefixDivide + "-" + subfixDivide;
            } else {
                BigDecimal prefixDivide = prefix.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : prefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                tent = prefixDivide + "";
            }
            pr.setTentNumAfter(tent);
        }
        // 处理紧急安置人数单位
        String resettledNum = pr.getResettledNumAfter();
        if (PlatformObjectUtils.isEmpty(resettledNum)) {
            pr.setResettledNumAfter("");
        } else {
            String[] resettSplit = resettledNum.split("-");
            String resettled = "";
            BigDecimal resettledPrefix = new BigDecimal(resettSplit[0]);
            if (resettSplit.length == 2) {
                BigDecimal resettledSubfix = new BigDecimal(resettSplit[1]);
                BigDecimal prefixMultiply = resettledPrefix.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : resettledPrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = resettledSubfix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = resettledPrefix.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : resettledPrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "";
            }
            pr.setResettledNumAfter(resettled);
        }
        // 死亡人数
//        String deathNum = pr.getDeathTollAfter();
//        if (PlatformObjectUtils.isEmpty(deathNum)) {
//            pr.setDeathTollAfter("");
//        } else {
//            String[] deathSplit = deathNum.split("-");
//            String death = "";
//            BigDecimal deathPrefix = new BigDecimal(deathSplit[0]);
//            if (deathSplit.length == 2) {
//                BigDecimal deathSubfix = new BigDecimal(deathSplit[1]);
//                BigDecimal prefixMultiply = deathPrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:deathPrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = deathSubfix.divide( new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                death = prefixMultiply + "-" + subfixMultiply;
//            } else {
//                BigDecimal prefixMultiply = deathPrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:deathPrefix.divide( new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                death = prefixMultiply + "";
//            }
//            pr.setDeathTollAfter(death);
//        }
//        // 受伤人数
//        String injureNum = pr.getInjuredNumAfter();
//        if (PlatformObjectUtils.isEmpty(injureNum)) {
//            pr.setInjuredNumAfter("");
//        } else {
//            String[] injureSplit = injureNum.split("-");
//            String injure = "";
//            BigDecimal injurePrefix = new BigDecimal(injureSplit[0]);
//            if (injureSplit.length == 2) {
//                BigDecimal injureSubfix = new BigDecimal(injureSplit[1]);
//                BigDecimal prefixMultiply = injurePrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:injurePrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = injureSubfix.divide( new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                injure = prefixMultiply + "-" + subfixMultiply;
//            } else {
//                BigDecimal prefixMultiply = injurePrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:injurePrefix.divide( new BigDecimal(10000), 1, RoundingMode.HALF_UP);
//                injure = prefixMultiply + "";
//            }
//            pr.setInjuredNumAfter(injure);
//        }
//        // 救援力量
//        String resuceNum = pr.getDeathTollAfter();
//        if (PlatformObjectUtils.isEmpty(resuceNum)) {
//            pr.setRescueForceAfter("");
//        } else {
//            String[] resuceSplit = resuceNum.split("-");
//            String resuce = "";
//            BigDecimal resucePrefix = new BigDecimal(resuceSplit[0]);
//            if (resuceSplit.length == 2) {
//                BigDecimal resuceSubfix = new BigDecimal(resuceSplit[1]);
//                BigDecimal prefixMultiply = resucePrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:resucePrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = resuceSubfix.divide( new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                resuce = prefixMultiply + "-" + subfixMultiply;
//            } else {
//                BigDecimal prefixMultiply = resucePrefix.compareTo(BigDecimal.ZERO)==0?BigDecimal.ZERO:resucePrefix.divide( new BigDecimal(10000), 4, RoundingMode.HALF_UP);
//                resuce = prefixMultiply + "";
//            }
//            pr.setRescueForceAfter(resuce);
//        }
    }

    /**
     * 数据单位转换：人转换为万人并保留1位小数
     */
    private void handleResultEntity(ResultEntity pr) {
        //需要的帐篷数
        String tentNum = pr.getTentNum();
        if (PlatformObjectUtils.isEmpty(tentNum)) {
            pr.setTentNum("");
        } else {
            String[] split = tentNum.split("-");
            String tent = "";
            BigDecimal prefix = new BigDecimal(split[0]);
            if (split.length == 2) {
                BigDecimal subfix = new BigDecimal(split[1]);
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                BigDecimal subfixDivide = subfix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                tent = prefixDivide + "-" + subfixDivide;
            } else {
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                tent = prefixDivide + "";
            }
            pr.setTentNum(tent);
        }

        //处理紧急安置人数
        String resettledNum = pr.getResettledNum();
        if (PlatformObjectUtils.isEmpty(resettledNum)) {
            pr.setResettledNum("");
        } else {
            String[] resettSplit = resettledNum.split("-");
            String resettled = "";
            BigDecimal resettledPrefix = new BigDecimal(resettSplit[0]);
            if (resettSplit.length == 2) {
                BigDecimal resettledSubfix = new BigDecimal(resettSplit[1]);
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = resettledSubfix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 4, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "";
            }
            pr.setResettledNum(resettled);
        }

        //死亡人数
//        String deathNum = pr.getDeathToll();
//        if (PlatformObjectUtils.isEmpty(deathNum)) {
//            pr.setDeathToll("");
//        }else{
//            String[] deathNumSplit = deathNum.split("-");
//            String death = "";
//            BigDecimal deathPrefix = new BigDecimal(deathNumSplit[0]);
//            if(deathNumSplit.length==2){
//                BigDecimal deathSubfix = new BigDecimal(deathNumSplit[1]);
//                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = deathSubfix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                death = prefixMultiply+"-"+subfixMultiply;
//            }else{
//                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                death = prefixMultiply+"";
//            }
//            pr.setDeathToll(death);
//        }
//
//        //受伤人数
//        String injureNum = pr.getDeathToll();
//        if (PlatformObjectUtils.isEmpty(injureNum)) {
//            pr.setInjuredNum("");
//        }else{
//            String[] injureSplit = injureNum.split("-");
//            String injure = "";
//            BigDecimal injurePrefix = new BigDecimal(injureSplit[0]);
//            if(injureSplit.length==2){
//                BigDecimal injureSubfix = new BigDecimal(injureSplit[1]);
//                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = injureSubfix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                injure = prefixMultiply+"-"+subfixMultiply;
//            }else{
//                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                injure = prefixMultiply+"";
//            }
//            pr.setInjuredNum(injure);
//        }
//
//        //救援人数
//        String rescueNum = pr.getRescueForce();
//        if (PlatformObjectUtils.isEmpty(rescueNum)) {
//            pr.setRescueForce("");
//        }else{
//            String[] rescueSplit = rescueNum.split("-");
//            String rescue = "";
//            BigDecimal rescuePrefix = new BigDecimal(rescueSplit[0]);
//            if(rescueSplit.length==2){
//                BigDecimal rescueSubfix = new BigDecimal(rescueSplit[1]);
//                BigDecimal prefixMultiply = rescuePrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                BigDecimal subfixMultiply = rescueSubfix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                rescue = prefixMultiply+"-"+subfixMultiply;
//            }else{
//                BigDecimal prefixMultiply = rescuePrefix.divide(new BigDecimal(10000),4, RoundingMode.HALF_UP);
//                rescue = prefixMultiply+"";
//            }
//            pr.setRescueForce(rescue);
//        }
    }

    /**
     * 数据单位转换：人转换为万人并保留1位小数
     */
    private void handleResultMainEntityVO(ResultMainEntityVO pr) {
        String tent = "";
        String tentNum = pr.getTentNumAfter();
        if (PlatformObjectUtils.isEmpty(tentNum)) {
            pr.setTentNumAfter("");
        } else {
            String[] split = tentNum.split("-");
            BigDecimal prefix = new BigDecimal(split[0]);
            if (split.length == 2) {
                BigDecimal subfix = new BigDecimal(split[1]);
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixDivide = subfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                tent = prefixDivide + "-" + subfixDivide;
            } else {
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                tent = prefixDivide + "";
            }
            pr.setTentNumAfter(tent);
        }
        // 处理紧急安置人数单位
        String resettledNum = pr.getResettledNumAfter();
        if (PlatformObjectUtils.isEmpty(resettledNum)) {
            pr.setResettledNumAfter("");
        } else {
            String[] resettSplit = resettledNum.split("-");
            String resettled = "";
            BigDecimal resettledPrefix = new BigDecimal(resettSplit[0]);
            if (resettSplit.length == 2) {
                BigDecimal resettledSubfix = new BigDecimal(resettSplit[1]);
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = resettledSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "";
            }
            pr.setResettledNumAfter(resettled);
        }
        // 死亡人数
        String deathNum = pr.getDeathTollAfter();
        if (PlatformObjectUtils.isEmpty(deathNum)) {
            pr.setDeathTollAfter("");
        } else {
            String[] deathSplit = deathNum.split("-");
            String death = "";
            BigDecimal deathPrefix = new BigDecimal(deathSplit[0]);
            if (deathSplit.length == 2) {
                BigDecimal deathSubfix = new BigDecimal(deathSplit[1]);
                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = deathSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                death = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                death = prefixMultiply + "";
            }
            pr.setDeathTollAfter(death);
        }
        // 受伤人数
        String injureNum = pr.getInjuredNumAfter();
        if (PlatformObjectUtils.isEmpty(injureNum)) {
            pr.setInjuredNumAfter("");
        } else {
            String[] injureSplit = injureNum.split("-");
            String injure = "";
            BigDecimal injurePrefix = new BigDecimal(injureSplit[0]);
            if (injureSplit.length == 2) {
                BigDecimal injureSubfix = new BigDecimal(injureSplit[1]);
                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = injureSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                injure = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                injure = prefixMultiply + "";
            }
            pr.setInjuredNumAfter(injure);
        }
        // 救援力量
        String resuceNum = pr.getDeathTollAfter();
        if (PlatformObjectUtils.isEmpty(resuceNum)) {
            pr.setRescueForceAfter("");
        } else {
            String[] resuceSplit = resuceNum.split("-");
            String resuce = "";
            BigDecimal resucePrefix = new BigDecimal(resuceSplit[0]);
            if (resuceSplit.length == 2) {
                BigDecimal resuceSubfix = new BigDecimal(resuceSplit[1]);
                BigDecimal prefixMultiply = resucePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = resuceSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resuce = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = resucePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resuce = prefixMultiply + "";
            }
            pr.setRescueForceAfter(resuce);
        }
    }

    /**
     * 数据单位转换：人转换为万人并保留1位小数
     */
    private void handlePrefectureResult(PrefectureResultEntity pr) {
        //需要的帐篷数
        String tentNum = pr.getTentNum();
        if (PlatformObjectUtils.isEmpty(tentNum)) {
            pr.setTentNum("");
        } else {
            String[] split = tentNum.split("-");
            String tent = "";
            BigDecimal prefix = new BigDecimal(split[0]);
            if (split.length == 2) {
                BigDecimal subfix = new BigDecimal(split[1]);
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixDivide = subfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                tent = prefixDivide + "-" + subfixDivide;
            } else {
                BigDecimal prefixDivide = prefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                tent = prefixDivide + "";
            }
            pr.setTentNum(tent);
        }

        //处理紧急安置人数
        String resettledNum = pr.getResettledNum();
        if (PlatformObjectUtils.isEmpty(resettledNum)) {
            pr.setResettledNum("");
        } else {
            String[] resettSplit = resettledNum.split("-");
            String resettled = "";
            BigDecimal resettledPrefix = new BigDecimal(resettSplit[0]);
            if (resettSplit.length == 2) {
                BigDecimal resettledSubfix = new BigDecimal(resettSplit[1]);
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = resettledSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = resettledPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                resettled = prefixMultiply + "";
            }
            pr.setResettledNum(resettled);
        }

        //死亡人数
        String deathNum = pr.getDeathToll();
        if (PlatformObjectUtils.isEmpty(deathNum)) {
            pr.setDeathToll("");
        } else {
            String[] deathNumSplit = deathNum.split("-");
            String death = "";
            BigDecimal deathPrefix = new BigDecimal(deathNumSplit[0]);
            if (deathNumSplit.length == 2) {
                BigDecimal deathSubfix = new BigDecimal(deathNumSplit[1]);
                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = deathSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                death = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = deathPrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                death = prefixMultiply + "";
            }
            pr.setDeathToll(death);
        }

        //受伤人数
        String injureNum = pr.getDeathToll();
        if (PlatformObjectUtils.isEmpty(injureNum)) {
            pr.setInjuredNum("");
        } else {
            String[] injureSplit = injureNum.split("-");
            String injure = "";
            BigDecimal injurePrefix = new BigDecimal(injureSplit[0]);
            if (injureSplit.length == 2) {
                BigDecimal injureSubfix = new BigDecimal(injureSplit[1]);
                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = injureSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                injure = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = injurePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                injure = prefixMultiply + "";
            }
            pr.setInjuredNum(injure);
        }

        //救援人数
        String rescueNum = pr.getRescueForce();
        if (PlatformObjectUtils.isEmpty(rescueNum)) {
            pr.setRescueForce("");
        } else {
            String[] rescueSplit = rescueNum.split("-");
            String rescue = "";
            BigDecimal rescuePrefix = new BigDecimal(rescueSplit[0]);
            if (rescueSplit.length == 2) {
                BigDecimal rescueSubfix = new BigDecimal(rescueSplit[1]);
                BigDecimal prefixMultiply = rescuePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                BigDecimal subfixMultiply = rescueSubfix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                rescue = prefixMultiply + "-" + subfixMultiply;
            } else {
                BigDecimal prefixMultiply = rescuePrefix.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP);
                rescue = prefixMultiply + "";
            }
            pr.setRescueForce(rescue);
        }

    }

    //附表4典型建筑物抗震能力分析数据处理
    private List<Map<String, List<List<String>>>> buildSeismicCapacityAnalysis(List<BuildingEntity> buildingEntityList, String level) {
        Map<String, List<BuildingEntity>> map = null;

        if ("1".equals(level)) {
            map = buildingEntityList.stream().collect(Collectors.groupingBy(vo -> vo.getProvince() + "_" + vo.getCity()));
        } else if ("2".equals(level)) {
            map = buildingEntityList.stream().collect(Collectors.groupingBy(vo -> vo.getProvince() + "_" + vo.getCity() + "_" + vo.getCounty()));
        }
        List<Map<String, List<List<String>>>> analysisList = new ArrayList<>();
        if (map != null) {
            AtomicInteger proNum = new AtomicInteger(0);
            map.forEach((k, v) -> {
                AtomicReference<AtomicInteger> structureNum = new AtomicReference<>(new AtomicInteger(1));
                Map<String, List<List<String>>> analysisMap = new HashMap<>();
                List<List<String>> strList = new ArrayList<>();
                final String[] structureType = {""};
                v.forEach(vo -> {
                    if (!structureType[0].equals(vo.getBuildingStructure())) {
                        structureType[0] = vo.getBuildingStructure();
                        proNum.getAndIncrement();
                        structureNum.set(new AtomicInteger(1));
                    }
                    String fieldSurveyName = vo.getFieldSurveyName();
                    //获取单体关联的调查点数据
                    SamplingEntity samplingEntity = buildingReqository.getSamplingEntityById(vo.getFieldSurveyId());
                    //SamplingEntity samplingEntity = samplingReqository.getSamplingEntityList(taskCode,fieldSurveyName,vo.getProvince(),vo.getCity(),vo.getCounty());
                    String furure = getFurure(samplingEntity, vo.getBuildingStructure());
                    String area = "";
                    String[] split = k.split("_");
                    if (split.length == 4) {
                        area = split[1] + "" + split[2];
                    } else if (split.length == 3) {
                        area = split[1] + "" + split[0];
                    }
                    List<AttachmentInfoEntity> structurePicList = new ArrayList<>();
                    if (StringUtils.isNotBlank(vo.getSpecifyPicture())) {
                        structurePicList = attachmentInfoRepository.findInIdList(Arrays.asList(vo.getSpecifyPicture().split(",")));
                    }
                    StringBuilder picBuilder = new StringBuilder();
                    if (structurePicList.size() > 0) {
                        structurePicList.forEach(entity -> {
                            String url = entity.getFileDirId() + entity.getAttachPath();
                            if (StringUtils.isNotBlank(url)) {
                                picBuilder.append(url).append(",");
                            }
                        });
                    }
                    String picPath = StringUtils.isNotBlank(picBuilder) ? picBuilder.substring(0, picBuilder.length() - 1) : "";
                    SeismicCapacityAnalysisForTable table = SeismicCapacityAnalysisForTable.builder()
                            .area(area).buildingStructure(getStructureName(Integer.valueOf(vo.getBuildingStructure())))
                            .seismicCapacity(vo.getSeismicCapacity()).specifyPicture(picPath)
                            .feature(furure).num(proNum.get() + "-" + structureNum.get().get()).build();
                    structureNum.get().getAndIncrement();
                    List<String> entityStringList = getEntityStringList(table);
                    strList.add(entityStringList);
                });
                analysisMap.put(k, strList);
                analysisList.add(analysisMap);
                proNum.getAndIncrement();
            });
        }
        return analysisList;
    }

//    private Map<String,List<List<String>>> buildSeismicCapacityAnalysis(String taskCode){
//        List<SeismicCapacityAnalysis> allData = reportManagementRepository.getAllDataByTaskCode(taskCode);
//        Map<String,List<List<String>>> map = new HashMap<>();
//        AtomicInteger num = new AtomicInteger(1);
//
//        allData.forEach(entity->{
//            String structureName = getStructureName(Integer.valueOf(entity.getBuildingStructure()));
//            String future = getFurure(entity);
//            SeismicCapacityAnalysisForTable table = SeismicCapacityAnalysisForTable.builder()
//                    .province(entity.getProvince()).num(num.getAndAdd(1)).buildingStructure(structureName)
//                    .seismicCapacity(entity.getSeismicCapacity()).specifyPicture("").feature(future).build();
//            List<String> entityStringList = getEntityStringList(table);
//            if(map.containsKey(entity.getProvince())){
//                List<List<String>> list = map.get(entity.getProvince());
//                list.add(entityStringList);
//                map.put(entity.getProvince(),list);
//            }else{
//                List<List<String>> list = new ArrayList<>();
//                list.add(entityStringList);
//                map.put(entity.getProvince(),list);
//            }
//        });
//        return map;
//    }

    /**
     * 根据结构类型获取典型结构特征
     */
    private String getFurure(SamplingEntity entity, String buildingStructure) {
        String structureName = "";
        switch (Integer.parseInt(buildingStructure)) {
            case 0:
                structureName = "高层结构";
                return entity.getHighFeature();
            case 1:
                structureName = "钢结构";
                return entity.getSteelFeature();
            case 2:
                structureName = "混凝土结构";
                return entity.getConcreteFeature();
            case 3:
                structureName = "砖混结构";
                return entity.getMasonryFeature();
            case 4:
                structureName = "砖木结构";
                return entity.getBrickWoodFeature();
            case 5:
                structureName = "土结构";
                return entity.getSoilFeature();
            case 6:
                structureName = "木结构";
                return entity.getWoodFeature();
            case 7:
                structureName = "石结构";
                return entity.getStoneFeature();
            case 8:
                structureName = "其他结构";
                return entity.getOtherFeature();
            default:
                structureName = "高层结构";
                return entity.getHighFeature();
        }
    }

    private StructureType getTownRatio(HosPeoEntity hosPeo) {
        StructureType structureType = StructureType.builder()
                .province(hosPeo.getProvince()).city(hosPeo.getCity()).prefecture(hosPeo.getPrefecture())
                .highRatio(hosPeo.getDhpTownHighTatio() + "").steelRatio(hosPeo.getDhpTownSteelTatio() + "")
                .mutilRatio(hosPeo.getDhpTownBetonTatio() + "").brickRatio(hosPeo.getDhpTownBrickTatio() + "")
                .birckWoodRatio(hosPeo.getDhpTownMasonryTatio() + "").soilRatio(hosPeo.getDhpTownSoilTatio() + "")
                .woodRatio(hosPeo.getDhpTownWoodTatio() + "").stoneRatio(hosPeo.getDhpTownStoneTatio() + "")
                .otherRatio(hosPeo.getDhpTownOtherTatio() + "").build();
        return structureType;
    }

    /**
     * 获取人口和建筑物概况中农村各建筑类别的占比
     */
    private StructureType getVillageRatio(HosPeoEntity hosPeo) {
        StructureType structureType = StructureType.builder()
                .province(hosPeo.getProvince()).city(hosPeo.getCity()).prefecture(hosPeo.getPrefecture())
                .highRatio(hosPeo.getDhpVillageHighTatio() + "").steelRatio(hosPeo.getDhpVillageSteelTatio() + "")
                .mutilRatio(hosPeo.getDhpVillageBetonTatio() + "").brickRatio(hosPeo.getDhpVillageBrickTatio() + "")
                .birckWoodRatio(hosPeo.getDhpVillageMasonryTatio() + "").soilRatio(hosPeo.getDhpVillageSoilTatio() + "")
                .woodRatio(hosPeo.getDhpVillageWoodTatio() + "").stoneRatio(hosPeo.getDhpVillageStoneTatio() + "")
                .otherRatio(hosPeo.getDhpVillageOtherTatio() + "").build();
        return structureType;
    }

    /**
     * 将实体中标有指定注解的属性封装在字符串类型的List集合中用于表格行中各个列的数据渲染
     */
    private List<String> getEntityStringList(Object obj) {
        List<String> list = new ArrayList<>();
        KeyDisaterStatics keyDisaterStatics = null;
        Suggestion suggestion = null;
        StructureType structureType = null;
        SeismicCapacityAnalysisForTable table = null;
        HosPeo hosPeo = null;
        Field[] fields = null;
        if (obj instanceof KeyDisaterStatics) {
            keyDisaterStatics = (KeyDisaterStatics) obj;
            fields = keyDisaterStatics.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Object valueObj = getFieldValue(keyDisaterStatics, name);
                list.add(PlatformObjectUtils.isEmpty(valueObj) ? "" : valueObj.toString());
            }
        } else if (obj instanceof Suggestion) {
            suggestion = (Suggestion) obj;
            fields = suggestion.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Object valueObj = getFieldValue(suggestion, name);
                list.add(PlatformObjectUtils.isEmpty(valueObj) ? "" : valueObj.toString());
            }
        } else if (obj instanceof StructureType) {
            structureType = (StructureType) obj;
            fields = structureType.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Object valueObj = getFieldValue(structureType, name);
                String value = PlatformObjectUtils.isEmpty(valueObj) ? "" : valueObj.toString();
                list.add(value);
            }
        } else if (obj instanceof SeismicCapacityAnalysisForTable) {
            table = (SeismicCapacityAnalysisForTable) obj;
            fields = table.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Object valueObj = getFieldValue(table, name);
                list.add(PlatformObjectUtils.isEmpty(valueObj) ? "" : valueObj.toString());
            }
        } else if (obj instanceof HosPeo) {
            hosPeo = (HosPeo) obj;
            fields = hosPeo.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Object valueObj = getFieldValue(hosPeo, name);
                list.add(PlatformObjectUtils.isEmpty(valueObj) ? "" : valueObj.toString());
            }
        }
        return list;
    }

    /**
     * @author Dongbj
     * @date 2023/2/1 14:56
     * @desc 备份代码，系统使用并且稳定后可删除
     */
    private Map getReportDataBak(String taskId, String dataSource, String level, String SimplifiedReportTemplate) throws IllegalAccessException {
        Map<String, Object> dataMap = new HashMap<>();
        //获取任务详情
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);
        String taskCode = preAssessTaskEntity.getTaskNum();
        //年度、名称
        String year = preAssessTaskEntity.getTaskYear();
        String name = preAssessTaskEntity.getTaskName();
        dataMap.put("year", year);
        dataMap.put("name", name);
        //当前时间
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String time = df.format(date);
        dataMap.put("time", time);
        //地震个数
        Integer num = resultRepository.prefectureResultCount(taskCode);
        String amount = String.valueOf(num);
        dataMap.put("amount", amount);
        //人口分布图、经济分布图
        String populationPath = mapManagementService.getPopulationPath(taskId);
        String economicsPath = mapManagementService.getEconomicsPath(taskId);
        dataMap.put("populationPath", populationPath);
        dataMap.put("economicsPath", economicsPath);
        //历史地震
        List<HistoricalSeismicData> historicalSeismicDataList = historicalSeismicDataService.judgeHistoricalSeismicData(taskId);
        StringBuilder historicalSeismicData = new StringBuilder();
        if (historicalSeismicDataList.size() > 0) {
            for (int i = 0; i < historicalSeismicDataList.size(); i++) {
                historicalSeismicData = historicalSeismicData.append(historicalSeismicDataList.get(i).getHsdTime() +
                        historicalSeismicDataList.get(i).getHsdReferencename() +
                        historicalSeismicDataList.get(i).getHsdSgrade() + "、");
            }
            historicalSeismicData.deleteCharAt(historicalSeismicData.length() - 1);
            historicalSeismicData.append("等");
        }
        dataMap.put("historicalSeismicData", historicalSeismicData.toString());
        buildYpgResultTable(dataSource, taskId, level, dataMap, taskCode);
        //文字部分
        Map<String, Object> map = suggestionAnalysisService.getDataByTaskNum(taskCode);
        //处理地震应急准备和处置要点数据
        String zhqjfx = getZhqjfxText(map.get("zhqjfx"));
        //地震应急准备和处置要点
        // dataMap.put("dzyjzbhczyd",map.get("zhqjfx"));
        dataMap.put("dzyjzbhczyd", zhqjfx);
        //地震应急准备建议
        String yjzbcz = getYjzbczText(map.get("yjzbcz"));
        dataMap.put("dzyjzbjy", yjzbcz);
        //地震应急处置建议
        String yjczdc = getYjczdcText(map.get("yjczdc"));
        dataMap.put("dzyjczjy", yjczdc);
        return dataMap;
    }

    private Map<String, List<List<String>>> getCityResultList(List<ResultMainEntityVO> cityResultEntityList, List<PrefectureResultEntity> prefectureResultEntityList) throws IllegalAccessException {
        List<String> strList = new ArrayList<>();
        Map<String, List<List<String>>> tempMap = new LinkedHashMap<>();
        if (cityResultEntityList != null) {
            Map<String, ResultMainEntityVO> resultMap = new HashMap<>();
            for (ResultMainEntityVO entity : cityResultEntityList) {
                //宏观位置
                String macroPosition = entity.getMacroPosition();
                if (StringUtils.isNotBlank(macroPosition)) {
                    String city = macroPosition.split(",")[1];
                    //震级
                    BigDecimal magnitude = entity.getMagnitude();
                    if (resultMap.containsKey(city + "_" + magnitude)) {
                        ResultMainEntityVO vo = resultMap.get(city + "_" + magnitude);
                        // 以地市为单位分别获取相同震级下的最大值和最小值
                        /**
                         * 重庆市,重庆市 5.5 59009-61741 177027-185224
                         * 重庆市,重庆市 6.0 87695-94869 263086-284607
                         * 重庆市,重庆市 6.5 76419-78609 229258-235829
                         */
                        reportHandle.compareAndSwap(vo, entity);
                        resultMap.put(city + "_" + magnitude, vo);
                    } else {
                        entity.setMacroPosition(city);
                        resultMap.put(city + "_" + magnitude, entity);
                    }
                }
            }
            String temp = "";
            if (resultMap.values().size() > 0) {
                LinkedHashMap<String, ResultMainEntityVO> collectMap = resultMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                        collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                //k=重庆市_5.5 v=ResultMainEntityVO
                Iterator<Map.Entry<String, ResultMainEntityVO>> iterator = collectMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, ResultMainEntityVO> next = iterator.next();
                    String key = next.getKey();
                    //地市或区县
                    //temp=key.split("_")[0];
                    ResultMainEntityVO vo = next.getValue();
                    strList = reportHandle.buildStrList(vo);
                    List<List<String>> tempList = new ArrayList<>();
                    tempList.add(strList);
                    tempMap.put(key, tempList);
//                    if(!tempMap.containsKey(temp)){
//                        List<List<String>> tempList = new ArrayList<>();
//                        tempList.add(strList);
//                        tempMap.put(temp,tempList);
//                    }else{
//                        List<List<String>> tempList = tempMap.get(temp);
//                        tempList.add(strList);
//                        tempMap.put(temp,tempList);
//                    }
                }
            }
        }

        if (prefectureResultEntityList != null) {
            Map<String, PrefectureResultEntity> resultMap = new HashMap<>();
            for (PrefectureResultEntity entity : prefectureResultEntityList) {
                String city = entity.getCity();
                if (StringUtils.isNotBlank(city)) {
                    //震级
                    BigDecimal magnitude = entity.getMagnitude();
                    if (resultMap.containsKey(city + "_" + magnitude)) {
                        PrefectureResultEntity pvo = resultMap.get(city + "_" + magnitude);
                        // 以地市为单位分别获取相同震级下的最大值和最小值
                        /**
                         * 重庆市,重庆市 5.5 59009-61741 177027-185224
                         * 重庆市,重庆市 6.0 87695-94869 263086-284607
                         * 重庆市,重庆市 6.5 76419-78609 229258-235829
                         */
                        reportHandle.compareAndSwap(pvo, entity);
                        resultMap.put(city + "_" + magnitude, pvo);
                    } else {
                        resultMap.put(city + "_" + magnitude, entity);
                    }
                }
            }
            if (resultMap.values().size() > 0) {
                LinkedHashMap<String, PrefectureResultEntity> collectMap = resultMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                        collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                //k=重庆市_5.5 v=ResultMainEntityVO
                Iterator<Map.Entry<String, PrefectureResultEntity>> iterator = collectMap.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, PrefectureResultEntity> next = iterator.next();
                    String city = next.getKey();
                    PrefectureResultEntity entity = next.getValue();
                    strList = reportHandle.buildStrList(entity);
                    if (!tempMap.containsKey(city)) {
                        List<List<String>> tempList = new ArrayList<>();
                        tempList.add(strList);
                        tempMap.put(city, tempList);
                    } else {
                        List<List<String>> tempList = tempMap.get(city);
                        tempList.add(strList);
                        tempMap.put(city, tempList);
                    }
                }
            }
        }
        return tempMap;
    }

    /**
     * 报告简本预评估结果表数据格式构建
     */
    public Map<String, List<List<String>>> getCityResultList1(List<ResultMainEntityVO> cityResultEntityList, List<ResultMainEntityVO> resultEntityList, List<PrefectureResultEntity> prefectureResultEntityList) throws IllegalAccessException {
        List<Map<String, List<List<String>>>> resultList = new ArrayList<>();
        String temp = "";
        //地市
        Map<String, List<List<String>>> tempMap = new LinkedHashMap<>();
        if (cityResultEntityList != null) {
            Map<String, ResultMainEntityVO> resultMap = new HashMap<>();
            for (ResultMainEntityVO entity : cityResultEntityList) {
                //宏观位置
                String macroPosition = entity.getMacroPosition();
                if (StringUtils.isNotBlank(macroPosition)) {
                    String city = macroPosition.split(",")[1];
                    //震级
                    BigDecimal magnitude = entity.getMagnitude();
                    if (resultMap.containsKey(city + "_" + magnitude)) {
                        ResultMainEntityVO vo = resultMap.get(city + "_" + magnitude);
                        // 以地市为单位分别获取相同震级下的最大值和最小值
                        /**
                         * 重庆市,重庆市 5.5 59009-61741 177027-185224
                         * 重庆市,重庆市 6.0 87695-94869 263086-284607
                         * 重庆市,重庆市 6.5 76419-78609 229258-235829
                         */
                        compareAndSwap(vo, entity);
                        resultMap.put(city + "_" + magnitude, vo);
                    } else {
                        resultMap.put(city + "_" + magnitude, entity);
                    }
                }
            }
            List<String> strList = new ArrayList<>();
            if (resultMap.values().size() > 0) {
                LinkedHashMap<String, ResultMainEntityVO> collectMap = resultMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                        collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                //k=重庆市_5.5 v=ResultMainEntityVO
                Iterator<Map.Entry<String, ResultMainEntityVO>> iterator = collectMap.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, ResultMainEntityVO> next = iterator.next();
                    String key = next.getKey();
                    temp = key.split("_")[0];
                    ResultMainEntityVO vo = next.getValue();
                    strList = buildStrList(vo);
                    if (!tempMap.containsKey(temp)) {
                        List<List<String>> tempList = new ArrayList<>();
                        tempList.add(strList);
                        tempMap.put(temp, tempList);
                    } else {
                        List<List<String>> tempList = tempMap.get(temp);
                        tempList.add(strList);
                        tempMap.put(temp, tempList);
                    }
                }
            }
        }
        if (prefectureResultEntityList != null) {
            Map<String, List<List<String>>> map = new HashMap<>();
            List<String> strList = new ArrayList<>();
            Map<String, PrefectureResultEntity> resultMap = new HashMap<>();
            for (PrefectureResultEntity entity : prefectureResultEntityList) {
                String city = entity.getCity();
                if (StringUtils.isNotBlank(city)) {
                    //震级
                    BigDecimal magnitude = entity.getMagnitude();
                    if (resultMap.containsKey(city + "_" + magnitude)) {
                        PrefectureResultEntity pvo = resultMap.get(city + "_" + magnitude);
                        // 以地市为单位分别获取相同震级下的最大值和最小值
                        /**
                         * 重庆市,重庆市 5.5 59009-61741 177027-185224
                         * 重庆市,重庆市 6.0 87695-94869 263086-284607
                         * 重庆市,重庆市 6.5 76419-78609 229258-235829
                         */
                        compareAndSwap(pvo, entity);
                        resultMap.put(city + "_" + magnitude, pvo);
                    } else {
                        resultMap.put(city + "_" + magnitude, entity);
                    }
                }
            }
            if (resultMap.values().size() > 0) {
                LinkedHashMap<String, PrefectureResultEntity> collectMap = resultMap.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).
                        collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                //k=重庆市_5.5 v=ResultMainEntityVO
                Iterator<Map.Entry<String, PrefectureResultEntity>> iterator = collectMap.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, PrefectureResultEntity> next = iterator.next();
                    String city = next.getKey();
                    PrefectureResultEntity entity = next.getValue();
                    strList = buildStrList(entity);
                    if (!tempMap.containsKey(city)) {
                        List<List<String>> tempList = new ArrayList<>();
                        tempList.add(strList);
                        tempMap.put(temp, tempList);
                    } else {
                        List<List<String>> tempList = tempMap.get(temp);
                        tempList.add(strList);
                        tempMap.put(temp, tempList);
                    }
                }
            }
        }
        return tempMap;
    }

    private void compareAndSwap(PrefectureResultEntity pvo, PrefectureResultEntity entity) throws IllegalAccessException {
        Field[] fields = pvo.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            CompareAndSwap compareAndSwap = field.getAnnotation(CompareAndSwap.class);
            field.setAccessible(true);
            if (compareAndSwap == null) {
                continue;
            }
            Object resultObj = getFieldValue(pvo, name);
            Object entityObj = getFieldValue(entity, name);
            if (resultObj == null) {
                field.set(pvo, entityObj == null ? "" : entityObj);
                continue;
            }
            if (entityObj == null) {
                continue;
            }

            String minResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[0] : resultObj.toString();
            String maxResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[1] : resultObj.toString();

            String minEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[0] : entityObj.toString();
            String maxEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[1] : entityObj.toString();

            Integer min = Integer.min(Integer.parseInt(minResult), Integer.parseInt(minEntity));
            Integer max = Integer.max(Integer.parseInt(maxResult), Integer.parseInt(maxEntity));
            if (min.equals(max)) {
                field.set(pvo, min + "");
            } else {
                field.set(pvo, min + "-" + max);
            }

//            if (Double.parseDouble(minResult) > Double.parseDouble(maxEntity)) {
//                field.set(pvo, minEntity + "-" + maxResult);
//            }else  if (Double.parseDouble(maxResult) < Double.parseDouble(minEntity)) {
//                field.set(pvo, minResult + "-" + maxEntity);
//            }else  if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
//                field.set(pvo, minEntity + "-" + maxEntity);
//            }else if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
//                field.set(pvo, minEntity + "-" + maxResult);
//            }else if (Double.parseDouble(minResult) <Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
//                field.set(pvo, minResult + "-" + maxEntity);
//            }else if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
//                field.set(pvo, minResult + "-" + maxResult);
//            }
        }
    }

    /**
     * 构建指定格式的数据最终用于实现表的合并单元格
     */
    public List<Map<String, List<List<String>>>> getCityResultListV2(List<ResultMainEntityVO> cityResultEntityList, List<ResultMainEntityVO> resultEntityList, List<PrefectureResultEntity> prefectureResultEntityList) throws IllegalAccessException {
        List<Map<String, List<List<String>>>> resultList = new ArrayList<>();
        String temp = "";
        if (cityResultEntityList != null) {
            List<Map<String, ResultMainEntityVO>> voList = new ArrayList<>();
            Map<String, List<String>> tempMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : cityResultEntityList) {
                String macroPosition = mainEntity.getMacroPosition();
                String[] split = macroPosition.split(",");
                if (split.length >= 3) {
                    if (!tempMap.containsKey(split[1])) {
                        List<String> tempList = new ArrayList<>();
                        tempList.add(split[2]);
                        tempMap.put(split[1], tempList);
                    } else {
                        List<String> tempList = tempMap.get(split[1]);
                        if (!tempList.contains(split[2])) {
                            tempList.add(split[2]);
                            tempMap.put(split[1], tempList);
                        }
                    }
                }
            }
            Map<String, ResultMainEntityVO> resultMap = new HashMap<>();
            for (ResultMainEntityVO entity : cityResultEntityList) {
                //宏观位置
                String macroPosition = entity.getMacroPosition();
                String city = macroPosition.split(",")[1];
                if (tempMap.containsKey(city)) {
                    List<String> tempList = tempMap.get(city);
                    String str = String.join(",", tempList);
                    entity.setImportantArea(str);
                }
                //震级
                BigDecimal magnitude = entity.getMagnitude();
                if (resultMap.containsKey(city + "_" + magnitude)) {
                    ResultMainEntityVO vo = resultMap.get(city + "_" + magnitude);
                    // 以地市为单位分别获取相同震级下的最大值和最小值
                    /**
                     * 重庆市,重庆市 5.5 59009-61741 177027-185224
                     * 重庆市,重庆市 6.0 87695-94869 263086-284607
                     * 重庆市,重庆市 6.5 76419-78609 229258-235829
                     */
                    compareAndSwap2(vo, entity);
                } else {
                    resultMap.put(city + "_" + magnitude, entity);
                }
            }
            if (resultMap.values().size() > 0) {
                voList.add(resultMap);
            }

            if (PlatformObjectUtils.isNotEmpty(voList)) {
                List<List<String>> tempList = new ArrayList<>();
                Map<String, List<List<String>>> map = new HashMap<>();
                List<String> strList = new ArrayList<>();
                for (Map<String, ResultMainEntityVO> voMap : voList) {
                    Collection<ResultMainEntityVO> values = voMap.values();
                    List<ResultMainEntityVO> vos = values.stream().sorted(Comparator.comparing(ResultMainEntityVO::getMagnitude)).collect(Collectors.toList());
                    String city = vos.get(0).getMacroPosition().split(",")[1];
                    if ("".equals(temp)) {
                        temp = city;
                    }
                    if (!temp.equals(city)) {
                        map.put(temp, tempList);
                        tempList = new ArrayList<>();
                        resultList.add(map);
                        map = new HashMap<>();
                        temp = city;
                    }
                    Set<String> importArea = new HashSet<>();
                    for (ResultMainEntityVO vo : vos) {
                        strList = buildStrListV2(vo);
                        tempList.add(strList);
                    }
                }
                map.put(temp, tempList);
                resultList.add(map);
            }
        }
        if (resultEntityList != null) {
            List<Map<String, ResultMainEntityVO>> voList = new ArrayList<>();
            Map<String, List<String>> tempMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : resultEntityList) {
                String macroPosition = mainEntity.getMacroPosition();
                String[] split = macroPosition.split(",");
                //if(split.length>=2){
                if (!tempMap.containsKey(split[2])) {
                    List<String> tempList = new ArrayList<>();
                    tempList.add(split[2]);
                    tempMap.put(split[2], tempList);
                } else {
                    List<String> tempList = tempMap.get(split[2]);
                    if (!tempList.contains(split[2])) {
                        tempList.add(split[2]);
                        tempMap.put(split[2], tempList);
                    }
                }
                //}
            }
            Map<String, ResultMainEntityVO> resultMap = new HashMap<>();
            for (ResultMainEntityVO mainEntity : resultEntityList) {
                //宏观位置
                String macroPosition = mainEntity.getMacroPosition();
                mainEntity.setMacroPosition(macroPosition.split(",")[2]);
                String country = macroPosition.split(",")[2];
                if (tempMap.containsKey(country)) {
                    List<String> tempList = tempMap.get(country);
                    String str = String.join(",", tempList);
                    mainEntity.setImportantArea(str);
                }
                //震级
                BigDecimal magnitude = mainEntity.getMagnitude();
                if (resultMap.containsKey(country + "_" + magnitude)) {
                    ResultMainEntityVO entity = resultMap.get(country + "_" + magnitude);
                    //compareAndSwap(entity, mainEntity);
                    addData(entity, mainEntity);
                } else {
//                    if (resultMap.values().size() > 0) {
//                        voList.add(resultMap);
//                        //resultMap = new HashMap<>();
//                    }
                    resultMap.put(country + "_" + magnitude, mainEntity);
                }
            }
            if (resultMap.values().size() > 0) {
                voList.add(resultMap);
                resultMap = new HashMap<>();
            }
            if (PlatformObjectUtils.isNotEmpty(voList)) {
                List<List<String>> tempList = new ArrayList<>();
                Map<String, List<List<String>>> map = new HashMap<>();
                List<String> strList = new ArrayList<>();
                for (Map<String, ResultMainEntityVO> voMap : voList) {
                    Collection<ResultMainEntityVO> values = voMap.values();
                    List<ResultMainEntityVO> vos = values.stream().sorted(Comparator.comparing(ResultMainEntityVO::getMagnitude)).collect(Collectors.toList());
                    //ArrayList<ResultMainEntityVO> vos = Lists.newArrayList(values);
                    for (int i = 0; i < vos.size(); i++) {
//                        String city = vos.get(i).getMacroPosition();
//                        if ("".equals(temp)) {
//                            temp = city;
//                        }
//                        if (!temp.equals(city)) {
//                            map.put(temp, tempList);
//                            tempList = new ArrayList<>();
//                            resultList.add(map);
//                            map = new HashMap<>();
//                            temp = city;
//                        }
                        strList = buildStrListV3(vos.get(i));
                        tempList.add(strList);
                    }
                }
                map.put(temp, tempList);
                resultList.add(map);
            }
        }
        if (prefectureResultEntityList != null) {
            List<List<String>> tempList = new ArrayList<>();
            Map<String, List<List<String>>> map = new HashMap<>();
            List<String> strList = new ArrayList<>();
            for (PrefectureResultEntity entity : prefectureResultEntityList) {
//                String city = entity.getCity();
//                if ("".equals(temp)) {
//                    temp = city;
//                }
//                if (!temp.equals(city)) {
//                    map.put(temp, tempList);
//                    tempList = new ArrayList<>();
//                    resultList.add(map);
//                    map = new HashMap<>();
//                    temp = city;
//                }
                strList = buildStrListV2(entity);
                tempList.add(strList);
            }
            map.put(temp, tempList);
            resultList.add(map);
        }

        return resultList;
    }

    /**
     * 构建指定格式的数据最终用于实现表的合并单元格
     */
    private List<String> buildStrListV3(ResultMainEntityVO obj) {
        List<String> list = new ArrayList<>();
        ResultMainEntityVO vo = null;
        Field[] fields = null;
        if (obj instanceof ResultMainEntityVO) {
            vo = (ResultMainEntityVO) obj;
            fields = vo.getClass().getDeclaredFields();
            assert fields != null;
            String macroPositionStr = "";
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                TransformV2 transformV2 = field.getAnnotation(TransformV2.class);
                field.setAccessible(true);
                if (transformV2 == null) {
                    continue;
                }
                Object valueObj = getFieldValue(vo, name);
                String value = (valueObj == null ? "" : valueObj.toString());
                list.add(value);
            }
        }
        return list;
    }

    private void addData(ResultMainEntityVO resultMainEntity, ResultMainEntityVO entity) throws IllegalAccessException {
        if (resultMainEntity.getInjuredNumAfter().contains("-1-")) {
            String[] split = resultMainEntity.getInjuredNumAfter().split("-");
            if (split.length > 1) {
                resultMainEntity.setInjuredNumAfter("0" + "-" + resultMainEntity.getInjuredNumBefore());
            } else {
                resultMainEntity.setInjuredNumAfter("0");
            }
        }
        if (resultMainEntity.getDeathTollAfter().contains("-1-")) {
            String[] split = resultMainEntity.getDeathTollAfter().split("-");
            if (split.length > 1) {
                resultMainEntity.setDeathTollAfter("0" + "-" + resultMainEntity.getDeathTollBefore());
            } else {
                resultMainEntity.setDeathTollAfter("0");
            }
        }
        if (resultMainEntity.getResettledNumAfter().contains("-1-")) {
            String[] split = resultMainEntity.getResettledNumAfter().split("-");
            if (split.length > 1) {
                resultMainEntity.setResettledNumAfter("0" + "-" + resultMainEntity.getResettledNumBefore());
            } else {
                resultMainEntity.setResettledNumAfter("0");
            }
        }
        Field[] fields = resultMainEntity.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            AddData addData = field.getAnnotation(AddData.class);
            field.setAccessible(true);
            if (addData == null) {
                continue;
            }
            Object resultObj = getFieldValue(resultMainEntity, name);
            Object entityObj = getFieldValue(entity, name);
            if (resultObj == null && entityObj == null) {
                field.set(resultMainEntity, "0");
            } else {
                if (resultObj == null) {
                    if (entityObj != null) {
                        String finalValue = "";
                        String value = entityObj.toString();
                        if (StringUtils.isBlank(value)) {
                            finalValue += ("0");
                        } else {
                            String[] split = value.split("-");
                            if (split.length == 2) {
                                finalValue += (split[0] + "-" + split[1]);
                            } else if (split.length == 1) {
                                finalValue += (split[0]);
                            }
                        }
                        field.set(resultMainEntity, finalValue);
                    }
                } else {
                    String resultValue = resultObj.toString();
                    if ("resettledNumAfter".equals(name) || "tentNumAfter".equals(name)) {
                        if (resultValue.indexOf("-") > 0) {
                            BigDecimal prefix = new BigDecimal(resultValue.split("-")[0]).multiply(BigDecimal.valueOf(10000));
                            BigDecimal subfix = new BigDecimal(resultValue.split("-")[1]).multiply(BigDecimal.valueOf(10000));
                            resultValue = prefix.intValue() + "-" + subfix.intValue();
                        } else {
                            resultValue = new BigDecimal(resultValue).multiply(BigDecimal.valueOf(10000)).intValue() + "";
                        }
                    }
                    int min = -1;
                    int max = -1;
                    int entityMin = -1;
                    int entityMax = -1;
                    String finalValue = "";

                    if (StringUtils.isNotBlank(resultValue)) {
                        if (resultValue.split("-").length == 2) {
                            min = Integer.parseInt(resultValue.split("-")[0]);
                            max = Integer.parseInt(resultValue.split("-")[1]);
                        } else if (resultValue.split("-").length == 1) {
                            min = Integer.parseInt(resultValue.split("-")[0]);
                        } else {
                            min = Integer.parseInt(resultValue);
                        }
                    }
                    if (entityObj != null) {
                        String value = entityObj.toString();
                        if (StringUtils.isBlank(value)) {
                            if (min > 0 && max > 0) {
                                finalValue = "0";
                            }
                        } else {
                            String[] split = value.split("-");
                            if (split.length == 2) {
                                entityMin = Integer.parseInt(split[0]);
                                entityMax = Integer.parseInt(split[1]);
                                if (max == -1) {
                                    if (min == -1) {
                                        if (min <= entityMin) {
                                            finalValue = "0-" + entityMax;
                                        }
                                    } else {
                                        if (min <= entityMin) {
                                            finalValue = min + "-" + entityMax;
                                        }
                                        if (min >= entityMin) {
                                            finalValue = entityMin + "-" + entityMax;
                                        }
                                        if (min < entityMax && min >= entityMin) {
                                            finalValue = entityMin + "-" + entityMax;
                                        }
                                    }

                                } else {
                                    finalValue = Integer.min(min, entityMin) + "-" + Integer.max(max, entityMax);
                                }
                            } else if (split.length == 1) {
                                entityMin = Integer.parseInt(split[0]);
                                if (max == -1) {
                                    if (min == -1) {
                                        finalValue = ("0-" + entityMin);
                                    } else {
                                        finalValue = Integer.min(min, entityMin) + "-" + Integer.max(min, entityMin);
                                        //finalValue =  min<entityMin?min+"-"+entityMin:entityMin+"-"+min;
                                    }
                                } else {
                                    finalValue = Integer.min(min, entityMin) + "-" + Integer.max(max, entityMax);
//                                    finalValue = min>entityMin?entityMin+"-"+max:entityMin>max?min+"-"+entityMin:entityMin>min&&entityMin<max?min+"-"+max:"";
                                    //finalValue = min>=entityMin?(max>=entityMax?entityMin+"-"+max:entityMin+"-"+entityMax):(max>=entityMax?min+"-"+max:min+"-"+entityMax);
                                }
                            }
                        }
                    }
                    if ("resettledNumAfter".equals(name) || "tentNumAfter".equals(name)) {
                        if (finalValue.indexOf("-") > 0) {
                            BigDecimal prefix = new BigDecimal(finalValue.split("-")[0]).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_DOWN);
                            BigDecimal subfix = new BigDecimal(finalValue.split("-")[1]).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_DOWN);
                            finalValue = prefix + "-" + subfix;
                        } else {
                            finalValue = new BigDecimal(resultValue).divide(BigDecimal.valueOf(10000), 4, RoundingMode.HALF_DOWN) + "";
                        }
                    }
                    if (finalValue.contains("-")) {
                        if (finalValue.split("-")[0].equals(finalValue.split("-")[1])) {
                            finalValue = finalValue.split("-")[0];
                        }
                    }
                    field.set(resultMainEntity, finalValue);
                }
            }

        }
    }

//    private List<Map<String, List<List<String>>>> getMainResultList(List<ResultMainEntity> resultMainEntityVOS, List<ResultMainEntity> resultMainEntities, List<ResultEntity> resultEntities) throws IllegalAccessException {
//        String temp = "";
//        List<Map<String, List<List<String>>>> resultList = new ArrayList<>();
//        List<List<String>> tempList = new ArrayList<>();
//        Map<String, List<List<String>>> map = new HashMap<>();
//        List<String> strList = new ArrayList<>();
//        String longitude = "";
//        String latitude = "";
//        String macroPosition = "";
//        String llm = "";
//        if (resultMainEntityVOS != null) {
//            List<Map<String, ResultMainEntity>> voList = new ArrayList<>();
//            Map<String, ResultMainEntity> lmap = new HashMap<>();
//            for (ResultMainEntity entity : resultMainEntityVOS) {
//                longitude = entity.getLongitude();
//                latitude = entity.getLatitude();
//                macroPosition = entity.getMacroPosition();
//                //获取市
//                String city = macroPosition.split(",")[1];
//                BigDecimal magnitude = entity.getMagnitude();
//                llm = (longitude + "_" + latitude + "_" + city + "_" + magnitude);
//                if (!lmap.containsKey(llm)) {
//                    lmap.put(llm, entity);
//                } else {
//                    ResultMainEntity resultMainEntity = lmap.get(llm);
//                    compareAndSwap(resultMainEntity, entity);
//                    lmap.put(llm, resultMainEntity);
//                }
//            }
//            if (lmap.values().size() > 0) {
//                voList.add(lmap);
//            }
//            if (PlatformObjectUtils.isNotEmpty(voList)) {
//                for (Map<String, ResultMainEntity> voMap : voList) {
//                    Collection<ResultMainEntity> values = voMap.values();
//                    ArrayList<ResultMainEntity> vos = Lists.newArrayList(values);
//                    String city = vos.get(0).getMacroPosition();
//                    if ("".equals(temp)) {
//                        temp = city;
//                    }
//                    if (!temp.equals(city)) {
//                        map.put(temp, tempList);
//                        tempList = new ArrayList<>();
//                        resultList.add(map);
//                        map = new HashMap<>();
//                        temp = city;
//                    }
//                    strList = buildStrList(vos.get(0));
//                    tempList.add(strList);
//                }
//                map.put(temp, tempList);
//                resultList.add(map);
//            }
//        }
//        if (resultMainEntities != null) {
//            for (ResultMainEntity entity : resultMainEntities) {
//                longitude = entity.getLongitude();
//                latitude = entity.getLatitude();
//                macroPosition = entity.getMacroPosition();
//                llm = (longitude + "_" + latitude + "_" + macroPosition);
//                if ("".equals(temp)) {
//                    temp = llm;
//                }
//                if (!temp.equals(llm)) {
//                    map.put(temp, tempList);
//                    tempList = new ArrayList<>();
//                    resultList.add(map);
//                    map = new HashMap<>();
//                    temp = llm;
//                }
//                strList = buildStrList(entity);
//                tempList.add(strList);
//            }
//        }
//        if (resultEntities != null) {
//            for (ResultEntity entity : resultEntities) {
//                longitude = entity.getLongitude();
//                latitude = entity.getLatitude();
//                macroPosition = entity.getMacroPosition();
//                llm = (longitude + "_" + latitude + "_" + macroPosition);
//                if ("".equals(temp)) {
//                    temp = llm;
//                }
//                if (!temp.equals(llm)) {
//                    map.put(temp, tempList);
//                    tempList = new ArrayList<>();
//                    resultList.add(map);
//                    map = new HashMap<>();
//                    temp = llm;
//                }
//                strList = buildStrList(entity);
//                tempList.add(strList);
//            }
//        }
//        map.put(temp, tempList);
//        resultList.add(map);
//        return resultList;
//    }

    private Map<String, List<List<String>>> getMainResultList1(List<ResultMainEntity> resultMainEntityVOS, List<ResultMainEntity> resultMainEntities, List<ResultEntity> resultEntities) throws IllegalAccessException {
        Map<String, List<List<String>>> resultMap = new LinkedHashMap<>();
        Map<String, List<List<String>>> map = new HashMap<>();
        List<String> strList = new ArrayList<>();
        String longitude = "";
        String latitude = "";
        String macroPosition = "";
        String llm = "";
        if (resultMainEntityVOS != null) {
            List<Map<String, ResultMainEntity>> voList = new ArrayList<>();
            Map<String, ResultMainEntity> lmap = new HashMap<>();
            for (ResultMainEntity entity : resultMainEntityVOS) {
                longitude = new BigDecimal(entity.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                latitude = new BigDecimal(entity.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                entity.setLongitude(longitude);
                entity.setLatitude(latitude);
                macroPosition = entity.getMacroPosition();
                //获取市
                String city = macroPosition.split(",")[1];
                BigDecimal magnitude = entity.getMagnitude();
                llm = (longitude + "_" + latitude + "_" + city + "_" + magnitude);
                strList = buildStrList(entity);
                if (!lmap.containsKey(llm)) {
                    List<List<String>> list = new ArrayList<>();
                    list.add(strList);
                    resultMap.put(llm, list);
                } else {
                    List<List<String>> list = resultMap.get(llm);
                    list.add(strList);
                    resultMap.put(llm, list);
                }
            }
        }
        if (resultMainEntities != null) {
            for (ResultMainEntity entity : resultMainEntities) {
                longitude = new BigDecimal(entity.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                latitude = new BigDecimal(entity.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                entity.setLongitude(longitude);
                entity.setLatitude(latitude);
                macroPosition = entity.getMacroPosition();
                llm = (longitude + "_" + latitude + "_" + macroPosition);
                strList = buildStrList(entity);
                if (resultMap.containsKey(llm)) {
                    List<List<String>> list = resultMap.get(llm);
                    list.add(strList);
                    resultMap.put(llm, list);
                } else {
                    List<List<String>> list = new ArrayList<>();
                    list.add(strList);
                    resultMap.put(llm, list);
                }
            }
        }
        if (resultEntities != null) {
            for (ResultEntity entity : resultEntities) {
                longitude = new BigDecimal(entity.getLongitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                latitude = new BigDecimal(entity.getLatitude()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
                entity.setLongitude(longitude);
                entity.setLatitude(latitude);
                macroPosition = entity.getMacroPosition();
                llm = (longitude + "_" + latitude + "_" + macroPosition);
                strList = buildStrList(entity);
                if (resultMap.containsKey(llm)) {
                    List<List<String>> list = resultMap.get(llm);
                    list.add(strList);
                    resultMap.put(llm, list);
                } else {
                    List<List<String>> list = new ArrayList<>();
                    list.add(strList);
                    resultMap.put(llm, list);
                }
            }
        }
        return resultMap;
    }

    private void operate(String temp, String llm, Map<String, List<List<String>>> map, List<Map<String, List<List<String>>>> resultList, List<List<String>> tempList) {
        if ("".equals(temp)) {
            temp = llm;
        }
        if (!temp.equals(llm)) {
            map.put(temp, tempList);
            tempList = new ArrayList<>();
            resultList.add(map);
            map = new HashMap<>();
            temp = llm;
        }
    }

    private void compareAndSwap(ResultMainEntityVO resultMainEntity, ResultMainEntityVO entity) throws IllegalAccessException {
        Field[] fields = resultMainEntity.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            CompareAndSwap compareAndSwap = field.getAnnotation(CompareAndSwap.class);
            field.setAccessible(true);
            if (compareAndSwap == null) {
                continue;
            }
            Object resultObj = getFieldValue(resultMainEntity, name);
            Object entityObj = getFieldValue(entity, name);
            if (resultObj == null) {
                field.set(resultMainEntity, entityObj == null ? "" : entityObj);
                continue;
            }
            if (entityObj == null) {
                continue;
            }

            String minResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[0] : resultObj.toString();
            String maxResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[1] : resultObj.toString();

            String minEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[0] : entityObj.toString();
            String maxEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[1] : entityObj.toString();
            Integer min = Integer.min(Integer.parseInt(minResult), Integer.parseInt(minEntity));
            Integer max = Integer.max(Integer.parseInt(maxResult), Integer.parseInt(maxEntity));
            if (min.equals(max)) {
                field.set(resultMainEntity, min + "");
            } else {
                field.set(resultMainEntity, min + "-" + max);
            }

//            if (Integer.parseInt(minResult) >= Integer.parseInt(maxEntity)) {
//                field.set(resultMainEntity, minEntity + "-" + maxResult);
//            }else  if (Integer.parseInt(maxResult) <= Integer.parseInt(minEntity)) {
//                field.set(resultMainEntity, minResult + "-" + maxEntity);
//            }else  if (Integer.parseInt(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
//                field.set(resultMainEntity, minEntity + "-" + maxEntity);
//            }else if (Integer.parseInt(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
//                field.set(resultMainEntity, minEntity + "-" + maxResult);
//            }else if (Integer.parseInt(minResult) <Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
//                field.set(resultMainEntity, minResult + "-" + maxEntity);
//            }else if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
//                field.set(resultMainEntity, minResult + "-" + maxResult);
//            }
        }
    }

    /**
     * 比较并交换用于获取最小值和最大值
     */
    private void compareAndSwap2(ResultMainEntityVO resultMainEntity, ResultMainEntityVO entity) throws IllegalAccessException {
        Field[] fields = resultMainEntity.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            CompareAndSwap compareAndSwap = field.getAnnotation(CompareAndSwap.class);
            field.setAccessible(true);
            if (compareAndSwap == null) {
                continue;
            }
            Object resultObj = getFieldValue(resultMainEntity, name);
            Object entityObj = getFieldValue(entity, name);
            if (resultObj == null) {
                field.set(resultMainEntity, entityObj == null ? "" : entityObj);
                continue;
            }
            if (entityObj == null) {
                continue;
            }

            if ("".equals(resultObj)) {
                if (!"".equals(entityObj)) {
                    String minEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[0] : entityObj.toString();
                    String maxEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[1] : entityObj.toString();
                    if (minEntity.equals(maxEntity)) {
                        field.set(resultMainEntity, minEntity + "-" + maxEntity);
                    } else {
                        field.set(resultMainEntity, minEntity);
                    }
                } else {
                    field.set(resultMainEntity, "");
                }
            } else {
                if ("".equals(entityObj)) {
                    String minResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[0] : resultObj.toString();
                    String maxResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[1] : resultObj.toString();
                    if (minResult.equals(maxResult)) {
                        field.set(resultMainEntity, minResult + "-" + maxResult);
                    } else {
                        field.set(resultMainEntity, minResult);
                    }
                } else {
                    String minResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[0] : resultObj.toString();
                    String maxResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[1] : resultObj.toString();

                    String minEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[0] : entityObj.toString();
                    String maxEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[1] : entityObj.toString();

                    if (Double.parseDouble(minResult) > Double.parseDouble(maxEntity)) {
                        field.set(resultMainEntity, minEntity + "-" + maxResult);
                    }
                    if (Double.parseDouble(maxResult) < Double.parseDouble(minEntity)) {
                        field.set(resultMainEntity, minResult + "-" + maxEntity);
                    }
                    if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                        field.set(resultMainEntity, minEntity + "-" + maxEntity);
                    }
                    if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
                        field.set(resultMainEntity, minEntity + "-" + maxResult);
                    }
                    if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                        field.set(resultMainEntity, minResult + "-" + maxEntity);
                    }
                    if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                        field.set(resultMainEntity, minResult + "-" + maxEntity);
                    }
                }
            }
        }
    }

    /**
     * 比较并交换用于获取最小值和最大值
     */
    private void compareAndSwap(ResultMainEntity resultMainEntity, ResultMainEntity entity) throws IllegalAccessException {
        Field[] fields = resultMainEntity.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String name = field.getName();
            CompareAndSwap compareAndSwap = field.getAnnotation(CompareAndSwap.class);
            field.setAccessible(true);
            if (compareAndSwap == null) {
                continue;
            }
            Object resultObj = getFieldValue(resultMainEntity, name);
            Object entityObj = getFieldValue(entity, name);
            if (resultObj == null) {
                field.set(resultMainEntity, entityObj == null ? "" : entityObj);
                continue;
            }
            if (entityObj == null) {
                continue;
            }

            String minResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[0] : resultObj.toString();
            String maxResult = resultObj.toString().indexOf("-") > 0 ? resultObj.toString().split("-")[1] : resultObj.toString();

            String minEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[0] : entityObj.toString();
            String maxEntity = entityObj.toString().indexOf("-") > 0 ? entityObj.toString().split("-")[1] : entityObj.toString();

            if (Double.parseDouble(minResult) > Double.parseDouble(maxEntity)) {
                field.set(resultMainEntity, minEntity + "-" + maxResult);
            }
            if (Double.parseDouble(maxResult) < Double.parseDouble(minEntity)) {
                field.set(resultMainEntity, minResult + "-" + maxEntity);
            }
            if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                field.set(resultMainEntity, minEntity + "-" + maxEntity);
            }
            if (Double.parseDouble(minResult) > Double.parseDouble(minEntity) && Double.parseDouble(maxResult) > Double.parseDouble(maxEntity)) {
                field.set(resultMainEntity, minEntity + "-" + maxResult);
            }
            if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                field.set(resultMainEntity, minResult + "-" + maxEntity);
            }
            if (Double.parseDouble(minResult) < Double.parseDouble(minEntity) && Double.parseDouble(maxResult) < Double.parseDouble(maxEntity)) {
                field.set(resultMainEntity, minResult + "-" + maxEntity);
            }
        }
    }

    /**
     * 简本版本1中大文本数据的构建
     */
    private String getYjzbczText(Object obj) {
        StringBuilder build = new StringBuilder("\r\n");
        List<Map<String, String>> list = (List<Map<String, String>>) obj;
        if (PlatformObjectUtils.isNotEmpty(list)) {
            int i = 0;
            for (Map<String, String> map : list) {
                String areaName = map.get("areaName");
                if (areaName.contains("北京市") || areaName.contains("天津市") || areaName.contains("上海市") || areaName.contains("重庆市")) {
                    //去重
                    areaName = removeRepeat(areaName);
                }
                build.append(areaName).append("\r\n");
                build.append("1.地震应急组织体系和预案体系").append("\r\n");
                build.append("\t").append(map.get("emergencySystem") == null ? "" : map.get("emergencySystem")).append("\r\n");
                build.append("2.地震应急工作机制").append("\r\n");
                build.append("\t").append(map.get("emergencyWorkingMechanism") == null ? "" : map.get("emergencyWorkingMechanism")).append("\r\n");
                build.append("3.应急物资储备").append("\r\n");
                build.append("\t").append(map.get("emergencySuppliesReserve") == null ? "" : map.get("emergencySuppliesReserve")).append("\r\n");
                build.append("4.应急救援力量").append("\r\n");
                build.append("\t").append(map.get("emergencyRescueForce") == null ? "" : map.get("emergencyRescueForce")).append("\r\n");
                build.append("5.应急避难场所").append("\r\n");
                build.append("\t").append(map.get("emergencyShelter") == null ? "" : map.get("emergencyShelter")).append("\r\n");
                build.append("6.重点目标保障能力").append("\r\n");
                build.append("\t").append(map.get("supportability") == null ? "" : map.get("supportability")).append("\r\n");
                build.append("7.谣言、舆情应急能力").append("\r\n");
                build.append("\t").append(map.get("rumorEmergencyCapacity") == null ? "" : map.get("rumorEmergencyCapacity")).append("\r\n");
                build.append("8.科普宣教和演练").append("\r\n");
                build.append("\t").append(map.get("popularization") == null ? "" : map.get("popularization")).append("\r\n");
                build.append("9.其他地方特征应急准备措施").append("\r\n");
                build.append("\t").append(map.get("otherMeasures") == null ? "" : map.get("otherMeasures"));
                if (i != list.size() - 1) {
                    build.append("\r\n").append("\r\n");
                }
                i++;
            }
        }
        return build.toString();
    }

    /**
     * 简本版本1中大文本数据的构建
     */
    private String getYjczdcText(Object obj) {
        StringBuilder build = new StringBuilder("\r\n");
        List<Map<String, String>> list = (List<Map<String, String>>) obj;
        if (PlatformObjectUtils.isNotEmpty(list)) {
            int i = 0;
            for (Map<String, String> map : list) {
                String areaName = map.get("areaName");
                if (areaName.contains("北京市") || areaName.contains("天津市") || areaName.contains("上海市") || areaName.contains("重庆市")) {
                    //去重
                    areaName = removeRepeat(areaName);
                }
                build.append(areaName).append("\r\n");
                build.append("1.救援力量和物资投入").append("\r\n");
                build.append("\t").append(map.get("rescueForceMaterialInput") == null ? "" : map.get("rescueForceMaterialInput")).append("\r\n");
                build.append("2.地震灾害危重区域识别").append("\r\n");
                build.append("\t").append(map.get("earthquakeDisasterCriticalArea") == null ? "" : map.get("earthquakeDisasterCriticalArea")).append("\r\n");
                build.append("3.交通系统保障和抢修").append("\r\n");
                build.append("\t").append(map.get("trafficSystemSupportRepair") == null ? "" : map.get("trafficSystemSupportRepair")).append("\r\n");
                build.append("4.通信系统保障和抢修").append("\r\n");
                build.append("\t").append(map.get("communicationsSystemSupportRepair") == null ? "" : map.get("communicationsSystemSupportRepair")).append("\r\n");
                build.append("5.电力系统保障和抢修").append("\r\n");
                build.append("\t").append(map.get("powerSystemSupportRepair") == null ? "" : map.get("powerSystemSupportRepair")).append("\r\n");
                build.append("6.重要基础设施隐患排查").append("\r\n");
                build.append("\t").append(map.get("importantFacilitiesCheck") == null ? "" : map.get("importantFacilitiesCheck")).append("\r\n");
                build.append("7.气候特征应对").append("\r\n");
                build.append("\t").append(map.get("climateFeatureReply") == null ? "" : map.get("climateFeatureReply")).append("\r\n");
                build.append("8.民族特征应对").append("\r\n");
                build.append("\t").append(map.get("nationFeatureReply") == null ? "" : map.get("nationFeatureReply")).append("\r\n");
                build.append("9.谣言、舆情应对").append("\r\n");
                build.append("\t").append(map.get("rumorReply") == null ? "" : map.get("rumorReply")).append("\r\n");
                build.append("10.其他地方特征应对").append("\r\n");
                build.append("\t").append(map.get("otherFeatureReply") == null ? "" : map.get("otherFeatureReply"));
                if (i != list.size() - 1) {
                    build.append("\r\n").append("\r\n");
                }
                i++;
            }
        }
        return build.toString();
    }

    /**
     * 简本版本1中大文本数据的构建
     */
    private String getZhqjfxText(Object obj) {
        StringBuilder zhqjfx = new StringBuilder("\r\n");
        List<Map<String, String>> list = (List<Map<String, String>>) obj;
        if (PlatformObjectUtils.isNotEmpty(list)) {
            int i = 0;
            for (Map<String, String> map : list) {
                String areaName = map.get("areaName");
                if (areaName.contains("北京市") || areaName.contains("天津市") || areaName.contains("上海市") || areaName.contains("重庆市")) {
                    //去重
                    areaName = removeRepeat(areaName);
                }
                zhqjfx.append(areaName).append("\r\n");
                zhqjfx.append("1.建筑物破坏").append("\r\n");
                zhqjfx.append("\t").append(map.get("buildingDamage") == null ? "" : map.get("buildingDamage")).append("\r\n");
                zhqjfx.append("2.人员伤亡").append("\r\n");
                zhqjfx.append("\t").append(map.get("casualties") == null ? "" : map.get("casualties")).append("\r\n");
                zhqjfx.append("3.地质灾害").append("\r\n");
                zhqjfx.append("\t").append(map.get("geologicHazard") == null ? "" : map.get("geologicHazard")).append("\r\n");
                zhqjfx.append("4.次生灾害").append("\r\n");
                zhqjfx.append("\t").append(map.get("secondaryDisaster") == null ? "" : map.get("secondaryDisaster")).append("\r\n");
                zhqjfx.append("5.震后交通").append("\r\n");
                zhqjfx.append("\t").append(map.get("earthquakeTraffic") == null ? "" : map.get("earthquakeTraffic")).append("\r\n");
                zhqjfx.append("6.其他灾害情景").append("\r\n");
                zhqjfx.append("\t").append(map.get("otherDisaster") == null ? "" : map.get("otherDisaster"));
                if (i != list.size() - 1) {
                    zhqjfx.append("\r\n").append("\r\n");
                }
                i++;
            }
        }
        return zhqjfx.toString();
    }

    /**
     * 去重
     */
    private String removeRepeat(String areaName) {
        //非空判断
        if (areaName == null) {
            return null;
        }
        StringBuilder sbd = new StringBuilder();//创建一个空的StringBuilder
        for (int i = 0; i < areaName.length(); i++) {
            char c = areaName.charAt(i);
            if (areaName.indexOf(c) == areaName.lastIndexOf(c)) {//第一次出现的下标跟最后一次相等,表示当前字符没有出现重复,直接添加进StringBuilder中
                sbd.append(c);
            } else {//出现重复
                if (areaName.indexOf(c) == i) {//如果重复出现的字符的位置等于当先字符的索引值,即表示当前字符为重复字符出现的第一次,将其加入StringBuilder中
                    sbd.append(c);
                }
            }
        }
        return sbd.toString();
    }

    private List<String> buildStrList(Object obj) {
        List<String> list = new ArrayList<>();
        PrefectureResultEntity prefectureResultEntity = null;
        ResultMainEntity resultEntity = null;
        ResultEntity result = null;
        ResultMainEntityVO vo = null;
        Field[] fields = null;
        if (obj instanceof PrefectureResultEntity) {
            prefectureResultEntity = (PrefectureResultEntity) obj;
            fields = prefectureResultEntity.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Transform transform = field.getAnnotation(Transform.class);
                field.setAccessible(true);
                if (transform == null) {
                    continue;
                }
                Object valueObj = getFieldValue(prefectureResultEntity, name);
                list.add(equals(valueObj) ? "" : valueObj.toString());
            }
        } else if (obj instanceof ResultMainEntity) {
            resultEntity = (ResultMainEntity) obj;
            fields = resultEntity.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Transform transform = field.getAnnotation(Transform.class);
                field.setAccessible(true);
                if (transform == null) {
                    continue;
                }
                Object valueObj = getFieldValue(resultEntity, name);
                if (valueObj != null) {
                    list.add(equals(valueObj) ? "" : valueObj.toString());
                }

            }
        } else if (obj instanceof ResultEntity) {
            result = (ResultEntity) obj;
            fields = result.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Transform transform = field.getAnnotation(Transform.class);
                field.setAccessible(true);
                if (transform == null) {
                    continue;
                }
                Object valueObj = getFieldValue(result, name);
                if ("longitude".equals(name) || "latitude".equals(name)) {
                    //经纬度保留两位小数
                    BigDecimal titude = new BigDecimal(valueObj.toString()).setScale(2, RoundingMode.HALF_DOWN);
                    list.add(equals(valueObj) ? "" : titude.toString());
                } else {
                    list.add(equals(valueObj) ? "" : valueObj.toString());
                }
            }
        } else if (obj instanceof ResultMainEntityVO) {
            vo = (ResultMainEntityVO) obj;
            fields = vo.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                Transform transform = field.getAnnotation(Transform.class);
                field.setAccessible(true);
                if (transform == null) {
                    continue;
                }
                Object valueObj = getFieldValue(vo, name);
                if (valueObj != null) {
                    list.add(equals(valueObj) ? "" : valueObj.toString());
                }
            }
        }

        return list;
    }

    private List<String> buildStrListV2(Object obj) {
        List<String> list = new ArrayList<>();
        PrefectureResultEntity prefectureResultEntity = null;
        ResultMainEntity resultEntity = null;
        ResultEntity result = null;
        ResultMainEntityVO vo = null;
        Field[] fields = null;
        if (obj instanceof PrefectureResultEntity) {
            prefectureResultEntity = (PrefectureResultEntity) obj;
            fields = prefectureResultEntity.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                TransformV2 transformV2 = field.getAnnotation(TransformV2.class);
                field.setAccessible(true);
                if (transformV2 == null) {
                    continue;
                }
                Object valueObj = getFieldValue(prefectureResultEntity, name);
                list.add(equals(valueObj) ? "" : valueObj.toString());
            }
        } else if (obj instanceof ResultMainEntity) {
            resultEntity = (ResultMainEntity) obj;
            fields = resultEntity.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                TransformV2 transformV2 = field.getAnnotation(TransformV2.class);
                field.setAccessible(true);
                if (transformV2 == null) {
                    continue;
                }
                Object valueObj = getFieldValue(resultEntity, name);
                if (valueObj != null) {
                    list.add(equals(valueObj) ? "" : valueObj.toString());
                }

            }
        } else if (obj instanceof ResultEntity) {
            result = (ResultEntity) obj;
            fields = result.getClass().getDeclaredFields();
            assert fields != null;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                TransformV2 transformV2 = field.getAnnotation(TransformV2.class);
                field.setAccessible(true);
                if (transformV2 == null) {
                    continue;
                }
                Object valueObj = getFieldValue(result, name);
                if (valueObj != null) {
                    list.add(equals(valueObj) ? "" : valueObj.toString());
                }
            }
        } else if (obj instanceof ResultMainEntityVO) {
            vo = (ResultMainEntityVO) obj;
            fields = vo.getClass().getDeclaredFields();
            assert fields != null;
            String macroPositionStr = "";
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                String name = field.getName();
                TransformV2 transformV2 = field.getAnnotation(TransformV2.class);
                field.setAccessible(true);
                if (transformV2 == null) {
                    continue;
                }
                Object valueObj = getFieldValue(vo, name);
                String value = (valueObj == null ? "" : valueObj.toString());
                if (name.equals("macroPosition") && !"".equals(value)) {
                    macroPositionStr = value;
                    value = (value.split(",")[0] + "," + value.split(",")[1]);
                }

                list.add(value);
            }
        }

        return list;
    }

    /**
     * 反射时根据属性获取属性值
     */
    private static Object getFieldValue(Object thisClass, String fieldName) {
        Object value = new Object();
        Method method = null;
        try {
            String methodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            method = thisClass.getClass().getMethod("get" + methodName);
            value = method.invoke(thisClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    private Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    /**
     * 报告的上传
     */
    @Override
    public RestResponse uploadReport(MultipartFile file, String type, String level, String dataSource, String taskId) {
        PreAssessTaskEntity taskEntity = preAssessTaskRepository.findById(taskId);
        String reportId = "";
        RestResponse restResponse = null;
        if (file == null) {
            restResponse = RestResponse.fail("上传失败，请选择文件");
            return restResponse;
        }
        try {
            //获取文件名称
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            String filePrefix = fileName.split("\\.")[0];
            String fileType = fileName.split("\\.")[1];
            String localReportName = filePrefix + System.currentTimeMillis() + "." + fileType;
            //获取文件上传的本地路径
            String savePath = localDir;
            //上传文件
//            uploadFile(fileName,savePath,file);
            uploadFile(localReportName, savePath, file);
            //构建实体类
            ReportManagement reportManagement = new ReportManagement();
            HistoryUploadReport historyUploadReport = new HistoryUploadReport();
            historyUploadReport.setReportName(fileName);

            historyUploadReport.setLocalReportName(localReportName);
            historyUploadReport.setReportPath(localDir);
            Date uploadTime = new Date();
            historyUploadReport.setUploadTime(uploadTime);
            //1、简本 2、详本
            if ("1".equals(type)) {
                reportManagement.setUserUploadSimpleReportName(fileName);
                reportManagement.setSimpleReportUploadUserId(PlatformSessionContext.getUserID());
                reportManagement.setSimpleReportUploadTime(uploadTime);
                reportManagement.setLocalUserUploadSimpleReportName(localReportName);
            } else {
                reportManagement.setUserUploadMinuteReportName(fileName);
                reportManagement.setMinuteReportUploadUserId(PlatformSessionContext.getUserID());
                reportManagement.setMinuteReportUploadTime(uploadTime);
                reportManagement.setLocalUserUploadMinuteReportName(localReportName);
            }
            reportManagement.setReportStatus("2");
            reportManagement.setDataSource(dataSource);
            if (StringUtils.isNotBlank(taskEntity.getReportId())) {
                reportId = taskEntity.getReportId();
                reportManagement.setId(taskEntity.getReportId());
                reportManagementRepository.update(reportManagement);
            } else {
                //新增报告附件
                reportId = UUIDGenerator.getUUID();
                preAssessTaskRepository.insertReportId(taskId, reportId);
                reportManagement.setId(reportId);
                reportManagement.setAdministrativeLevel(level);
                reportManagement.setReportPath(localDir);
                reportManagementRepository.save(reportManagement);
            }
            //保存历史
            saveHistoryUploadReport(historyUploadReport, taskId, type);
        } catch (Exception e) {
            e.printStackTrace();
            restResponse = RestResponse.fail("文件上传失败");
            return restResponse;
        }
        return RestResponse.succeed(reportManagementRepository.getReportById(reportId));
    }

    private void uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, fileName);
        multipartFile.transferTo(file);
    }

    /**
     * 下载报告
     */
    @Override
    public void downloadReport(String reportId, String type, String def, HttpServletResponse res) throws IOException {
        ReportManagement report = reportManagementRepository.getReportById(reportId);
        String filePath = report.getReportPath();
        //todo 需要替换
        //filePath = "D:\\static";
        String fileName = "";
        //def 1系统默认 2、用户自己的
        if ("1".equals(def)) {
            //1:简本 2：详本
            if ("1".equals(type)) {
                fileName = report.getDefaultSimpleReportName();
            } else {
                fileName = report.getDefaultMinuteReportName();
            }
        } else {
            //1:简本 2：详本
            if ("1".equals(type)) {
                fileName = report.getLocalUserUploadSimpleReportName();
            } else {
                fileName = report.getLocalUserUploadMinuteReportName();
            }
        }
        FileUploadUtil.download(filePath + File.separator + fileName, res);
    }

    /**
     * 用户上传报告同时保存为历史报告
     */
    private void saveHistoryUploadReport(HistoryUploadReport historyUploadReport, String taskId, String type) {
        //历史报告保存
        historyUploadReport.setId(UUIDGenerator.getUUID());
        historyUploadReport.setTaskId(taskId);
        historyUploadReport.setUploadUserId(PlatformSessionContext.getUserID());
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        historyUploadReport.setUploadUserName(sUser.getUserName());
        historyUploadReport.setType(type);
        historyUploadReport.setOrgId(sUser.getOrgId());
        historyUploadReport.setOrgName(sUser.getOrgName());

        reportManagementRepository.saveHistoryUploadReport(historyUploadReport);
    }

    /**
     * 根据任务id获取历史报告
     */
    @Override
    public Map<String, Object> getHistoryReportByTaskId(String taskId, int curPage, int pageSize) {
        return reportManagementRepository.getHistoryReportByTaskId(taskId, curPage, pageSize);
    }

    /**
     * 下载历史报告
     */
    @Override
    public void downloadHistoryReport(String reportId, HttpServletResponse res) {
        HistoryUploadReport report = reportManagementRepository.getHistoryUploadReportById(reportId);
        String filePath = report.getReportPath();
        String fileName = report.getLocalReportName();
        FileUploadUtil.download(filePath + File.separator + fileName, res);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitReview(String reportId) {
        reportManagementRepository.submitReview(reportId);
        boolean b = preAssessTaskService.updateTaskStatus("2", reportId);//更新任务状态为审核中
        if (b) {
            //获取任务信息
            PreAssessTaskEntity taskEntity = preAssessTaskRepository.getPreAssessTaskByReportId(reportId);
            //根据角色名称获取角色对象id YPG_COUN_GL_ROLE_NAME
            String roleName = FxfzConstants.YPG_COUN_GL_ROLE_NAME;
            String roleId = sysRoleService.getRoleIdByNameAndSysid(roleName);
            //当前登录人
            String userId = PlatformSessionContext.getUserID();
            String userJson = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            //根据角色id查询其关联的用户
            List<SUser> sRoleUser = sysRoleService.getSRoleUser(roleId);
            if (sRoleUser != null && sRoleUser.size() >= 1) {
                for (int i = 0; i < sRoleUser.size(); i++) {
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setMessageGenerator(sUser.getUserId());
                    messageEntity.setMessageReceiver(sRoleUser.get(i).getUserId());
                    //{任务管理员}提交了{任务名称}任务的预评估结果，请您审核。
                    messageEntity.setMessageContent(sUser.getUserName() + "提交了" + taskEntity.getTaskName() + "任务的预评估结果，请您审核。");
                    messageService.addMessage(messageEntity);
                }
            }
        }
    }

    @Override
    public ReportManagement getReport(String reportId, String reportStatus, String reviewStatus) {
        return reportManagementRepository.getReport(reportId, reportStatus, reviewStatus);
    }

    private JSONObject getSubArea(List<String> taskIdList) {
        JSONObject jsonObject = new JSONObject();
        List<Map<String, Object>> objects = reportManagementRepository.getSubArea(taskIdList);
        if (PlatformObjectUtils.isEmpty(objects)) {
            return null;
        }
        AtomicInteger provinceNum = new AtomicInteger(0);
        AtomicInteger cityNum = new AtomicInteger(0);
        AtomicInteger areaNum = new AtomicInteger(objects.size());
        Map<String, Map<String, List<String>>> mapMap = new HashMap<>();
        for (Map map : objects) {
            String province = String.valueOf(map.get("province"));
            String city = String.valueOf(map.get("city"));
            String area = String.valueOf(map.get("area"));

            Map<String, List<String>> listMap;
            List<String> list;
            if (mapMap.containsKey(province)) {
                listMap = mapMap.get(province);
                if (listMap.containsKey(city)) {
                    list = listMap.get(city);
                } else {
                    list = new ArrayList<>();
                    cityNum.getAndIncrement();
                }
            } else {
                listMap = new HashMap<>();
                list = new ArrayList<>();
                provinceNum.getAndIncrement();
                cityNum.getAndIncrement();
            }
            list.add(area);
            listMap.put(city, list);
            mapMap.put(province, listMap);
        }
        jsonObject.put("mapMap", mapMap);
        jsonObject.put("num", provinceNum.get() + "_" + cityNum.get() + "_" + areaNum.get());
        return jsonObject;
    }

    //向产品信息服务传输生成的报告信息
    public void transReportMsgToCpxx(String picPath, String fileName, String keyword) throws Exception {
        String userId = PlatformSessionContext.getUserID();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        //获取创建人单位
        String orgName = sUser.getOrgName();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("cpxxRestUrl") + "/infAchievement/dockingOtherSystem";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        //String picPath = "D:\\static\\预评估现场调查报告20231009.docx";
        File newfile = new File(picPath);
        Map<String, String> valueMap = new HashMap<>();
        valueMap.put("dataOrigin", "5");
        valueMap.put("publishingUnit", orgName);
        valueMap.put("createUser", userId);
        valueMap.put("achievementName", fileName);
        valueMap.put("keyword", keyword);
        Map<String, MultipartFile> fileParams = new HashMap<>();
        //本地文件转为MultipartFile
        MultipartFile file = RemoteTransfer.pathToMultipartFile(newfile);
        fileParams.put("file", file);
        String res = RemoteTransfer.uploadFile(url, fileParams, valueMap, null);
    }

    private List<PreAssessTaskEntity> getTaskEntity(String taskId) {
        List<PreAssessTaskEntity> subTask = preAssessTaskRepository.getSubTask(taskId);
        if (PlatformObjectUtils.isNotEmpty(subTask) && subTask.size() > 0) {
            return subTask;
        }
        return null;
    }

    /**
     * 创建详本报告
     */
    @Override
    public RestResponse createDetailedReport(String taskId, String level, String modelName, String attachId, String taskName, HttpServletResponse response) throws Exception {
        StringBuilder msgDetail = new StringBuilder();
        List<PreAssessTaskEntity> subTask = getTaskEntity(taskId);
        JSONObject subArea = new JSONObject();
        List<String> taskIdList = null;
        List<String> taskNumList = null;
        PreAssessTaskEntity task = preAssessTaskRepository.findById(taskId);
        if (PlatformObjectUtils.isNotEmpty(subTask) && subTask.size() > 0) {
            taskIdList = subTask.stream().map(PreAssessTaskEntity::getId).collect(Collectors.toList());
            taskNumList = subTask.stream().map(PreAssessTaskEntity::getTaskNum).collect(Collectors.toList());
            subArea = getSubArea(taskIdList);
        } else {
            subArea = getSubArea(Arrays.asList(taskId));
        }

        //Map<String, String> pathMap = mapManagementService.getPathByLabel(taskId);
        Table<String, String, String> pathMap = mapManagementService.getPathByLabel1(taskId);
        List<YpgReport> reportList = new ArrayList<>();
        String taskCode = task.getTaskNum();
        if (PlatformObjectUtils.isEmpty(task)) {
            return ResponseCreator.createFailResponse("报告生成失败，任务不存在");
        }
        TrafficAnalysis tanalysis = countLandslideRepository.getTrafficAnalysisByTaskId(taskId, null);
        List<YpgResultRoad> ypgResultRoadList = countLandslideMapService.getYpgResultRoadListByTaskGeom(taskId, null);
        List<RiskEnterpriseData> riskEnterpriseData = riskEnterpriseDataRepository.getriskData(taskId);
        List<GasstationData> gassData = this.getGassData(taskId);
        String areaNum = (String) subArea.get("num");
        Map<String, Map<String, List<String>>> mapMap = (Map<String, Map<String, List<String>>>) subArea.get("mapMap");
        List<AreaVO> voList = new ArrayList<>();
        StringBuilder cityMsgDetails = new StringBuilder();
        StringBuilder countyMsgDetails = new StringBuilder();
        if (mapMap.values().size() > 0) {
            mapMap.forEach((k, v) -> {
                cityMsgDetails.append(k).append("省涉及市分别为");
                v.forEach((k1, v1) -> {
                    cityMsgDetails.append(k1).append("、");
                    v1.forEach(v11 -> {
                        countyMsgDetails.append(v11).append("、");
                        AreaVO vo = new AreaVO();
                        vo.setProvince(k);
                        vo.setCity(k1);
                        vo.setCounty(v11);
                        voList.add(vo);
                    });
                });
            });
        }
        String cityDetails = PlatformObjectUtils.isNotEmpty(cityMsgDetails) ? cityMsgDetails.substring(0, cityMsgDetails.length() - 1) : "";
        String countyDetails = PlatformObjectUtils.isNotEmpty(countyMsgDetails) ? countyMsgDetails.substring(0, countyMsgDetails.length() - 1) : "";
        //获取在任务范围内的乡村街道
        //乡镇详情
        StringBuilder townMsgDetails = new StringBuilder("");
        List<String> townList = areaMapService.getAllByTaskDirtrict(task.getGeom());
        Integer townNum = 0;
        if (PlatformObjectUtils.isNotEmpty(townList) && townList.size() > 0) {
            //乡镇个数
            townNum = PlatformObjectUtils.isNotEmpty(townList) ? townList.size() : 0;
            String townDetails = String.join("、", townList);
            //乡镇详情
            townMsgDetails.append(townDetails);
        } else {
            msgDetail.append("任务区域范围内获取不到乡镇信息");
        }
        PictureRenderData distirctPic = null;
        //图1.1 工作区行政区划图
        String districtPic = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("0", "临时名称") : "";
        if (StringUtils.isNotBlank(districtPic)) {
            distirctPic = new PictureRenderData(500, 320, districtPic);
            //distirctPic = new PictureRenderData(500, 320, "D:\\image\\b1ae30220c8593cfbd4b8cea3bd12ca4.jpg");
        }
//        else{
//            msgDetail.append(",").append("取不到工作区行政区划图");
//        }
        PictureRenderData dxPic = null;
        //图1.1 工作区行政区划图
        String dx = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("3", "临时名称") : "";
        if (StringUtils.isNotBlank(dx)) {
            dxPic = new PictureRenderData(500, 320, dx);
            //dxPic = new PictureRenderData(500, 320, "D:\\image\\b1ae30220c8593cfbd4b8cea3bd12ca4.jpg");
        }
//        else{
//            msgDetail.append(",").append("取不到工作区行政区划图");
//        }

//        PictureRenderData disaterDamagePicture = null;
//        //图4.1 遭遇烈度 VI 度地震地质灾害风险分布图
//        String disaterDamage = PlatformObjectUtils.isNotEmpty(pathMap)?pathMap.get("15"):"";
//        if(StringUtils.isNotBlank(disaterDamage)){
//            String[] pathList = disaterDamage.split(",");
//            for(String path : pathList){
//                disaterDamagePicture = new PictureRenderData(500, 320, path);
//            }
//
//        }
//        else{
//            msgDetail.append(",").append("取不到遭遇烈度 VI 度地震地质灾害风险分布图");
//        }
        PictureRenderData trafficImage = null;
        //图1.10 工作区交通分布图
        String trafficIma = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("5", "临时名称") : "";
        if (StringUtils.isNotBlank(trafficIma)) {
            trafficImage = new PictureRenderData(500, 320, trafficIma);
        }
        StringBuilder cityMsg = new StringBuilder("");
        cityMsg.append(areaNum.split("_")[0]).append("个省").append(areaNum.split("_")[1]).append("个市").append(areaNum.split("_")[2]).append("个县");

        List<YpgArea> areaList = new ArrayList<>();
        List<YpgArea1> areaList1 = new ArrayList<>();
        List<Map<String, Object>> popList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> economyList = new ArrayList<Map<String, Object>>();
        List<PopulationDetails> populationDetailsList = new ArrayList<>();
        List<YpgArea2> areaList2 = new ArrayList<>();
        List<Map<String, Object>> reportEvaluationList = new ArrayList<Map<String, Object>>();
        List<Traffic> reportTrafficList = new ArrayList<>();
        List<Map<String, Object>> reportReservoirList = new ArrayList<>();
        List<Map<String, Object>> reportSchoolList = new ArrayList<>();
        List<Map<String, Object>> reportDisasterList = new ArrayList<>();
        List<Earthquake> hfutureeList = new ArrayList<>();
        List<Earthquake> historyEarthList = new ArrayList<>();
        AtomicInteger reservoNum = new AtomicInteger(0);
        Set<String> reservorSet = new HashSet();
        AtomicInteger schNum = new AtomicInteger(0);
        Set<String> schoolSet = new HashSet();
        //历史地质灾害参数
        AtomicInteger disasterNum = new AtomicInteger(0);
        StringBuilder disasterDetails = new StringBuilder();
        AtomicInteger personNum = new AtomicInteger(0);
        AtomicInteger houseNum = new AtomicInteger(0);
        StringBuilder damageLevel = new StringBuilder();
        StringBuilder mostBuilder = new StringBuilder();
        StringBuilder damageLevelDetails = new StringBuilder();
        String master = "";
        String slave = "";
        String ddTails = "";
        List<EmergencyDisaster> reportPlanSystemList = new ArrayList<>();
        List<EmergencyDisaster> reportMechanismList = new ArrayList<>();
        List<EmergencyDisaster> reportImplementationList = new ArrayList<>();
        List<EmergencyDisaster> reportSafeguardsList = new ArrayList<>();
        List<EmergencyDisaster> reportPreventionList = new ArrayList<>();
        List<EmergencyDisaster> reportMedicalhelpList = new ArrayList<>();
        List<EmergencyDisaster> reportDemandList = new ArrayList<>();
        List<EmergencyDisaster> reportDevelopmentList = new ArrayList<>();
        List<EmergencyDisaster> reportSupportabilityList = new ArrayList<>();
        List<EmergencyDisaster> reportPublicOpinionList = new ArrayList<>();
        List<EmergencyDisaster> reportScienceList = new ArrayList<>();
        List<EmergencyDisaster> reportOtherList = new ArrayList<>();
        List<Map<String, Object>> reportReservesList = new ArrayList<>();
        List<Map<String, Object>> reportRescueList = new ArrayList<>();
        List<Map<String, Object>> reportEquipList = new ArrayList<>();
        List<Map<String, Object>> reportSanctuaryList = new ArrayList<>();
        List<Map<String, Object>> reportMedicalList = new ArrayList<>();
        AtomicInteger num = new AtomicInteger(1);
        AtomicInteger weatherNum = new AtomicInteger(1);
        AtomicInteger buildingFutureNum = new AtomicInteger(1);
        AtomicInteger trafficNum = new AtomicInteger(1);
        BiMap<String, String> structureMap = getStructureMap();
        StringBuilder gd = new StringBuilder();
        StringBuilder sd = new StringBuilder();
        StringBuilder xd = new StringBuilder();
        StringBuilder ql = new StringBuilder();
        List<Road> allRoadList = new ArrayList<>();
        List<GeologicalEntity> allGeoList = new ArrayList<>();
        //根据预评估任务查询关联的抽样调查点信息
        List<SamplingEntity> samplingList = new ArrayList<>();
        //如果任务存在子任务则查询子任务的调研点否则查询父任务的调研点  针对于详本报告来说目前只应用于第二章和第三章
        if (PlatformObjectUtils.isNotEmpty(taskIdList)) {
            for (String id : taskIdList) {
                List<SamplingEntity> tempResult = samplingReqository.getSamplingListByTaskId(id);
                if (PlatformObjectUtils.isNotEmpty(tempResult)) {
                    samplingList.addAll(tempResult);
                }
            }
        } else {
            samplingList = samplingReqository.getSamplingListByTaskId(taskId);
        }
        samplingList = samplingList.stream().distinct().collect(Collectors.toList());
        Boolean isCounty = true;
        AtomicInteger reservoirNum = new AtomicInteger(1);
        AtomicInteger schoolNum = new AtomicInteger(1);
        if (PlatformObjectUtils.isNotEmpty(voList)) {
            for (int i = 0; i < voList.size(); i++) {
                String province = voList.get(i).getProvince();
                String city = voList.get(i).getCity();
                String county = voList.get(i).getCounty();
                //根据省市县获取区县概况信息的地形地貌特征字段文字内容
                CountiesCondition qxCountiesCodition = countiesConditionRepository.getQxCountiesCodition(province, city, county);
                if (PlatformObjectUtils.isEmpty(qxCountiesCodition)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【区县概况信息】未维护，请到【统计数据管理 - 综合概况信息 - 区(县)概况信息】模块中维护。");
                    msgDetail.append(",").append(province).append("-").append(city).append("-").append(county).append("的区县概况信息未维护。");
                }
                String landform = qxCountiesCodition == null ? "" : qxCountiesCodition.getCcLandform();
                String weather = qxCountiesCodition == null ? "" : qxCountiesCodition.getCcClimate();
                String traff = qxCountiesCodition == null ? "" : qxCountiesCodition.getCcTraffic();
                String seismotectonics = qxCountiesCodition == null ? "" : qxCountiesCodition.getCcSeismotectonics();
                String historyEarth = qxCountiesCodition == null ? "" : qxCountiesCodition.getCcHistory();
                YpgArea ypgArea = YpgArea.builder().areaNameTitle("1.2." + num.getAndIncrement() + county).landform(landform).build();
                YpgArea1 ypgArea1 = YpgArea1.builder().areaNameTitle("1.3." + weatherNum.getAndIncrement() + county).weather(weather).build();
                Traffic traffic = Traffic.builder().areaNameTitle("1.7." + trafficNum.get() + county).trafficDetails(traff).build();
                areaList.add(ypgArea);
                areaList1.add(ypgArea1);
                reportTrafficList.add(traffic);
                //表1.4 工作区交通概况统计表
                List<Road> roadList = roadMapService.getRoadByDistirct(province, city, county);
                if (PlatformObjectUtils.isNotEmpty(roadList)) {
                    allRoadList.addAll(roadList);
                } else {
                    roadList = roadMapService.getRoadByDistirct(province, city, "");
                    if (PlatformObjectUtils.isEmpty(roadList)) {
                        roadList = roadMapService.getRoadByDistirct(province, "", "");
                    } else {
                        allRoadList.addAll(roadList);
                    }
                    if (PlatformObjectUtils.isEmpty(roadList)) {
                        msgDetail.append(province).append(city).append(county).append("道路信息未维护。");
                    } else {
                        allRoadList.addAll(roadList);
                    }
                    isCounty = false;
                }
                Earthquake earthquake = Earthquake.builder().countyName(county).seismotectonicsFeature(seismotectonics).build();
                hfutureeList.add(earthquake);
                Earthquake historyEarthquake = Earthquake.builder().countyName(county).seismotectonicsFeature(historyEarth).build();
                historyEarthList.add(historyEarthquake);
                //人口和建筑物概况
                HosPeoEntity hosPeo = hosPeoRepository.findHosPeo(province, city, county);
                if (PlatformObjectUtils.isEmpty(hosPeo)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【人口和建筑物概况】未维护，请到【人口和建筑物概况】模块中维护。");
                    msgDetail.append(",").append(province).append("-").append(city).append("-").append(county).append("的人口和建筑物概况未维护。");
                }
                Map<String, Object> map = new HashMap<String, Object>();
                //省
                map.put("province", province);
                //市
                map.put("city", city);
                //区县
                map.put("county", county);
                map.put("totalPopulation", PlatformObjectUtils.isNotEmpty(hosPeo) ? (PlatformObjectUtils.isNotEmpty(hosPeo.getDhpTotalPop()) ? hosPeo.getDhpTotalPop() : "") : "");
                popList.add(map);

                PopulationDetails populationDetails = new PopulationDetails();
                populationDetails.setAreaNameBody(county).setFutureDetails(qxCountiesCodition == null ? "" : (StringUtils.isNotBlank(qxCountiesCodition.getCcNation()) ? qxCountiesCodition.getCcNation() : ""));
                populationDetailsList.add(populationDetails);

                //Gdp
                GdpEntity gdpEntity = gdpRepositpory.getGdpByDivision(province, city, county);
                if (PlatformObjectUtils.isEmpty(gdpEntity)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【GDP数据】未维护，请到【GDP数据】模块中维护。");
                    msgDetail.append(",").append(province).append("-").append(city).append("-").append(county).append("的GDP数据未维护。");
                }
                Map<String, Object> economyMap = new HashMap<String, Object>();
                //省
                economyMap.put("province", province);
                //市
                economyMap.put("city", city);
                //区县
                economyMap.put("county", county);
                economyMap.put("totalGdp", PlatformObjectUtils.isNotEmpty(gdpEntity) ? (PlatformObjectUtils.isNotEmpty(gdpEntity.getGdp()) ? gdpEntity.getGdp() : "") : "");
                economyMap.put("avgGdp", PlatformObjectUtils.isNotEmpty(gdpEntity) ? (PlatformObjectUtils.isNotEmpty(gdpEntity.getPeoAvgGdp()) ? gdpEntity.getPeoAvgGdp() : "") : "");
                economyList.add(economyMap);
                //建筑物特征和抗震能力评价  这个调查点不能任务勾选的，而是任务区域中各个区县下抽样调查点
                List<SamplingEntity> samplingListByArea = samplingReqository.getByArea(province, city, county);
                Set<String> futureSet = new HashSet<>();
                Map<String, String> futureMap = new HashMap<>();
                Map<String, List<String>> singlePicMap = new HashMap<>();
                List<BuildingResultVo> buildingResultVoList = new ArrayList<>();
                List<BuildingStructure> structureList = new ArrayList<>();
                String details = "";
                if (PlatformObjectUtils.isEmpty(samplingListByArea) || samplingListByArea.size() == 0) {
                    msgDetail.append(",").append(province).append("-").append(city).append("-").append(county).append("获取不到抽样调查点信息。");
                } else {
                    //List<SamplingEntity> dxdList = samplingListByArea.stream().filter(samplingEntity ->  samplingEntity.getProvince().equals(province) && samplingEntity.getCity().equals(city) && samplingEntity.getArea().equals(county)).collect(Collectors.toList());
                    //获取房屋结构
                    List<String> msgList = new ArrayList<>();
                    samplingListByArea.forEach(samplingEntity -> {
                        //建筑物单体
                        List<BuildingResultVo> buildingResultVos = buildingReqository.queryBuildingData(samplingEntity.getId());
                        if (PlatformObjectUtils.isEmpty(buildingResultVos)) {
                            if (!msgList.contains(samplingEntity.getFieldSurveyName() + "获取不到建筑物单体数据")) {
                                msgList.add(samplingEntity.getFieldSurveyName() + "获取不到建筑物单体数据");
                            }
                        } else {
                            buildingResultVoList.addAll(buildingResultVos);
                            Map<String, List<BuildingResultVo>> singeMap = buildingResultVos.stream().collect(Collectors.groupingBy(BuildingResultVo::getBuildingStructure));
                            singeMap.forEach((k, v) -> {
                                List<String> picPathList = new ArrayList<>();
                                v.forEach(entity -> {
                                    String specifyPicture = entity.getSpecifyPicture();
                                    if (StringUtils.isNotBlank(specifyPicture)) {
                                        String[] picIdArr = specifyPicture.split(",");
                                        for (String picId : picIdArr) {
                                            AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(picId);
                                            if (PlatformObjectUtils.isNotEmpty(attach)) {
                                                String picPath = attach.getFileDirId() + attach.getAttachPath();
                                                picPathList.add(picPath);
                                            }
                                        }
                                    }
                                });
                                if (singlePicMap.containsKey(k)) {
                                    List<String> tempPicList = singlePicMap.get(k);
                                    tempPicList.addAll(picPathList);
                                    singlePicMap.put(k, tempPicList);
                                } else {
                                    singlePicMap.put(k, picPathList);
                                }
                            });
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getHighStructure())) {
                            futureSet.add("高层结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getHighFeature())) {
                            if (futureMap.containsKey("高层结构")) {
                                String structureFuture = futureMap.get("高层结构");
                                structureFuture += ("、" + samplingEntity.getHighFeature());
                                futureMap.put("高层结构", structureFuture);
                            } else {
                                futureMap.put("高层结构", samplingEntity.getHighFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getSteelStructure())) {
                            futureSet.add("钢结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getSteelFeature())) {
                            if (futureMap.containsKey("钢结构")) {
                                String structureFuture = futureMap.get("钢结构");
                                structureFuture += ("、" + samplingEntity.getSteelFeature());
                                futureMap.put("钢结构", structureFuture);
                            } else {
                                futureMap.put("钢结构", samplingEntity.getSteelFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getConcreteStructure())) {
                            futureSet.add("多层钢筋混凝土结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getConcreteFeature())) {
                            if (futureMap.containsKey("多层钢筋混凝土结构")) {
                                String structureFuture = futureMap.get("多层钢筋混凝土结构");
                                structureFuture += ("、" + samplingEntity.getConcreteFeature());
                                futureMap.put("多层钢筋混凝土结构", structureFuture);
                            } else {
                                futureMap.put("多层钢筋混凝土结构", samplingEntity.getConcreteFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getMasonryStructure())) {
                            futureSet.add("砖混结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getMasonryFeature())) {
                            if (futureMap.containsKey("砖混结构")) {
                                String structureFuture = futureMap.get("砖混结构");
                                structureFuture += ("、" + samplingEntity.getMasonryFeature());
                                futureMap.put("砖混结构", structureFuture);
                            } else {
                                futureMap.put("砖混结构", samplingEntity.getMasonryFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getBrickWoodStructure())) {
                            futureSet.add("砖木结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getBrickWoodFeature())) {
                            if (futureMap.containsKey("砖木结构")) {
                                String structureFuture = futureMap.get("砖木结构");
                                structureFuture += ("、" + samplingEntity.getBrickWoodFeature());
                                futureMap.put("砖木结构", structureFuture);
                            } else {
                                futureMap.put("砖木结构", samplingEntity.getBrickWoodFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getSoilStructure())) {
                            futureSet.add("土结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getSoilFeature())) {
                            if (futureMap.containsKey("土结构")) {
                                String structureFuture = futureMap.get("土结构");
                                structureFuture += ("、" + samplingEntity.getSoilFeature());
                                futureMap.put("土结构", structureFuture);
                            } else {
                                futureMap.put("土结构", samplingEntity.getSoilFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getWoodStructure())) {
                            futureSet.add("木结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getWoodFeature())) {
                            if (futureMap.containsKey("木结构")) {
                                String structureFuture = futureMap.get("木结构");
                                structureFuture += ("、" + samplingEntity.getWoodFeature());
                                futureMap.put("木结构", structureFuture);
                            } else {
                                futureMap.put("木结构", samplingEntity.getWoodFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getStoneStructure())) {
                            futureSet.add("石结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getStoneFeature())) {
                            if (futureMap.containsKey("石结构")) {
                                String structureFuture = futureMap.get("石结构");
                                structureFuture += ("、" + samplingEntity.getStoneFeature());
                                futureMap.put("石结构", structureFuture);
                            } else {
                                futureMap.put("石结构", samplingEntity.getStoneFeature());
                            }
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getOtherStructure())) {
                            futureSet.add("其他结构");
                        }
                        if (StringUtils.isNotBlank(samplingEntity.getOtherFeature())) {
                            if (futureMap.containsKey("其他结构")) {
                                String structureFuture = futureMap.get("其他结构");
                                structureFuture += ("、" + samplingEntity.getOtherFeature());
                                futureMap.put("其他结构", structureFuture);
                            } else {
                                futureMap.put("其他结构", samplingEntity.getOtherFeature());
                            }
                        }
                    });
                    StringBuilder structureDetails = new StringBuilder();
                    List<String> futureList = new ArrayList<>(futureSet);
                    structureDetails.append(String.join("、", futureList));
                    if (structureDetails.length() > 0) {
                        details = structureDetails.substring(0, structureDetails.length() - 1);
                    }
                    if (PlatformObjectUtils.isNotEmpty(futureList)) {
                        for (String future : futureList) {
                            BuildingStructure buildingStructure = new BuildingStructure();
                            String structureFuture = futureMap.get(future);
                            buildingStructure.setStructureName(future);
                            buildingStructure.setStructureFeature(structureFuture);
                            buildingStructure.setAreaNameBody(county);
                            String funtureIndex = structureMap.get(future);
                            List<String> picList = singlePicMap.get(funtureIndex);
                            List<Map<String, PictureRenderData>> structurePics = new ArrayList<>();
                            if (PlatformObjectUtils.isNotEmpty(picList)) {
                                picList.forEach(pic -> {
                                    //图片
                                    if (StringUtils.isNotBlank(pic)) {
                                        Map<String, PictureRenderData> picMap = new HashMap<>();
                                        picMap.put("picture", new PictureRenderData(255, 160, pic));
                                        structurePics.add(picMap);
                                    }
                                });
                            }
                            buildingStructure.setStructurePicList(structurePics);
                            structureList.add(buildingStructure);
                        }
                    }
                    if (msgList.size() > 0) {
                        msgDetail.append(msgList.toString());
                    }
                }
                YpgArea2 area2 = new YpgArea2();
                area2.setStructureList(structureList);
                area2.setAreaNameTitle("1.6.1." + buildingFutureNum.get() + county).setAreaNameBody(county).setStructureDetails(details).setStructureNum(futureSet.size() + "");
                areaList2.add(area2);
                Map<String, List<BuildingResultVo>> strucMap = buildingResultVoList.stream().collect(Collectors.groupingBy(BuildingResultVo::getBuildingStructure));
                strucMap.forEach((k, v) -> {
                    int typeList = v.size();
                    String type = structureMap.inverse().get(k);
                    //k是结构类型
                    long goodNum = v.stream().filter(buildingResultVo -> "好".equals(buildingResultVo.getSeismicCapacity())).count();
                    long bestNum = v.stream().filter(buildingResultVo -> "较好".equals(buildingResultVo.getSeismicCapacity())).count();
                    long normalNum = v.stream().filter(buildingResultVo -> "一般".equals(buildingResultVo.getSeismicCapacity())).count();
                    long badNum = v.stream().filter(buildingResultVo -> "较差".equals(buildingResultVo.getSeismicCapacity())).count();
                    long awfullyNum = v.stream().filter(buildingResultVo -> "差".equals(buildingResultVo.getSeismicCapacity())).count();
                    //设置保留位数
                    DecimalFormat df = new DecimalFormat("0.00");
                    String format = typeList == 0 ? "0" : df.format((float) goodNum / typeList);
                    String goodPercent = Double.valueOf(format) * 100 + "%";
                    if (goodPercent.indexOf(".0") > 0) {
                        goodPercent = goodPercent.split("\\.")[0];
                    }
                    goodPercent = goodPercent + "%";
                    format = typeList == 0 ? "0" : df.format((float) bestNum / typeList);
                    String bestPercent = Double.valueOf(format) * 100 + "%";
                    if (bestPercent.indexOf(".0") > 0) {
                        bestPercent = bestPercent.split("\\.")[0];
                    }
                    bestPercent = bestPercent + "%";
                    format = typeList == 0 ? "0" : df.format((float) normalNum / typeList);
                    String normalPercent = Double.valueOf(format) * 100 + "%";
                    if (normalPercent.indexOf(".0") > 0) {
                        normalPercent = normalPercent.split("\\.")[0];
                    }
                    normalPercent = normalPercent + "%";
                    format = typeList == 0 ? "0" : df.format((float) badNum / typeList);
                    String badPercent = Double.valueOf(format) * 100 + "%";
                    if (badPercent.indexOf(".0") > 0) {
                        badPercent = badPercent.split("\\.")[0];
                    }
                    badPercent = badPercent + "%";
                    format = typeList == 0 ? "0" : df.format((float) awfullyNum / typeList);
                    String awfullyPercent = Double.valueOf(format) * 100 + "%";
                    if (awfullyPercent.indexOf(".0") > 0) {
                        awfullyPercent = awfullyPercent.split("\\.")[0];
                    }
                    awfullyPercent = awfullyPercent + "%";
                    Map<String, Object> evaluationMap = new HashMap<String, Object>();
                    //省
                    evaluationMap.put("province", province);
                    //市
                    evaluationMap.put("city", city);
                    //区县
                    evaluationMap.put("county", county);
                    evaluationMap.put("structuerType", type);
                    evaluationMap.put("good", goodPercent);
                    evaluationMap.put("best", bestPercent);
                    evaluationMap.put("normal", normalPercent);
                    evaluationMap.put("bad", badPercent);
                    evaluationMap.put("awfully", awfullyPercent);
                    reportEvaluationList.add(evaluationMap);
                });
                //水库
                List<ReservoirEntity> allData = reservoirMapService.getAllData(province, city, county);
                if (PlatformObjectUtils.isEmpty(allData)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【水库数据】未维护。");
                    msgDetail.append(province).append("-").append(city).append("-").append(county).append("的水库数据未维护。");
                } else {
                    allData.forEach(entity -> {
                        reservorSet.add(entity.getResScale());
                        reservoNum.getAndIncrement();
                        Map<String, Object> reservoirMap = new HashMap<String, Object>();
                        reservoirMap.put("num", reservoirNum.getAndIncrement());
                        //省
                        reservoirMap.put("province", province);
                        //市
                        reservoirMap.put("city", city);
                        //区县
                        reservoirMap.put("county", county);
                        reservoirMap.put("reservoirName", entity.getResName());
                        reservoirMap.put("capacity", entity.getResCapacity());
                        reservoirMap.put("structure", entity.getResResultType());
                        reservoirMap.put("type", entity.getResScale());
                        reportReservoirList.add(reservoirMap);
                    });
                }
                //学校
                List<SchoolEntity> schoolList = schoolMapService.getAllData(province, city, county);
                if (PlatformObjectUtils.isEmpty(schoolList)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【学校数据】未维护。");
                    msgDetail.append(province).append("-").append(city).append("-").append(county).append("的学校数据未维护。");
                } else {
                    schoolList.forEach(entity -> {
                        schoolSet.add(entity.getSchType());
                        schNum.getAndIncrement();
                        Map<String, Object> schoolMap = new HashMap<String, Object>();
                        schoolMap.put("num", schoolNum.getAndIncrement());
                        //省
                        schoolMap.put("province", province);
                        //市
                        schoolMap.put("city", city);
                        //区县
                        schoolMap.put("county", county);
                        schoolMap.put("schoolName", entity.getSchName());
                        schoolMap.put("type", entity.getSchType());
                        schoolMap.put("stuNum", entity.getSchStuNum());
                        schoolMap.put("boarding", entity.getSchIsboarding());
                        reportSchoolList.add(schoolMap);
                    });
                }
                //1.10历史地质灾害概况
                List<GeologicalEntity> geoList = geologicalMapService.getAllData(province, city, county);
                if (PlatformObjectUtils.isEmpty(geoList)) {
                    //return RestResponse.fail(province+"、"+city+"、"+county+"的【地质灾害数据数据】未维护。");
                    msgDetail.append(province).append("-").append(city).append("-").append(county).append("的地质灾害数据数据未维护。");
                } else {
                    disasterNum.getAndAdd(geoList.size());
                    allGeoList.addAll(geoList);
                    AtomicInteger disNum = new AtomicInteger(1);
                    geoList.forEach(entity -> {
                        Map<String, Object> disasterMap = new HashMap<String, Object>();
                        disasterMap.put("num", disNum.getAndIncrement());
                        //省
                        disasterMap.put("province", province);
                        //市
                        disasterMap.put("city", city);
                        //区县
                        disasterMap.put("county", county);
                        disasterMap.put("name", entity.getDgdName());
                        disasterMap.put("type", entity.getDgdDisasterType());
                        disasterMap.put("position", "");
                        disasterMap.put("level", entity.getDgdDangerLevel());
                        reportDisasterList.add(disasterMap);
                    });
                }
                //第七章
                List<ScSeismicsetout> seismicSetoutData = seismicSetoutRepository.getAllData(province, city, county);
                if (PlatformObjectUtils.isEmpty(seismicSetoutData) || seismicSetoutData.size() == 0) {
                    String area = "";
                    if (province.equals(city)) {
                        area = province;
                    } else {
                        area = province + "、" + city;
                    }
                    //return RestResponse.fail(area+"、"+county+"的【应急准备情况】未维护。");
                    msgDetail.append(area).append("-").append(county).append("的应急准备情况未维护。");
                }
                if (PlatformObjectUtils.isNotEmpty(seismicSetoutData) && seismicSetoutData.size() > 0) {
                    AtomicInteger atomicInteger11 = new AtomicInteger(1);
                    AtomicInteger atomicInteger12 = new AtomicInteger(1);
                    AtomicInteger atomicInteger13 = new AtomicInteger(1);
                    AtomicInteger atomicInteger14 = new AtomicInteger(1);
                    AtomicInteger atomicInteger15 = new AtomicInteger(1);
                    seismicSetoutData.forEach(entity -> {
                        EmergencyDisaster ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScDzyjzztxhyatx());
                        reportPlanSystemList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScDzyjgzjz());
                        reportMechanismList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScYjylkzqk());
                        reportImplementationList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScSmxyjbzqk());
                        reportSafeguardsList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScCszhffqk());
                        reportPreventionList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScMedicalhelp());
                        reportMedicalhelpList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScYjdcxq());
                        reportDemandList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScBzxtjsqk());
                        reportDevelopmentList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScZdmbbznl());
                        reportSupportabilityList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScYyyqyjnl());
                        reportPublicOpinionList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScKpxjhyl());
                        reportScienceList.add(ed);
                        ed = new EmergencyDisaster();
                        ed.setAreaName(entity.getPrefecture());
                        ed.setCategory(entity.getScQtdftzyjzbcs());
                        reportOtherList.add(ed);
                        List<ScSupplies> wzList = seismicSetoutRepository.getWz(entity.getScId());
                        if (PlatformObjectUtils.isNotEmpty(wzList)) {
                            wzList.forEach(scSeismicsetout -> {
                                Map<String, Object> staticsMap = new HashMap<>();
                                staticsMap.put("num", atomicInteger11.getAndAdd(1));
                                staticsMap.put("province", province);
                                staticsMap.put("city", city);
                                staticsMap.put("county", county);
                                staticsMap.put("name", scSeismicsetout.getScSuppliesName());
                                staticsMap.put("brand", scSeismicsetout.getScSuppliesBrand());
                                staticsMap.put("amount", scSeismicsetout.getScSuppliesNumber());
                                staticsMap.put("unit", scSeismicsetout.getScSuppliesUnit());
                                staticsMap.put("note", scSeismicsetout.getScSuppliesNote());
                                reportReservesList.add(staticsMap);
                            });
                        }
                        List<ScRescue> scRescueList = seismicSetoutRepository.getScRescue(entity.getScId());
                        if (PlatformObjectUtils.isNotEmpty(scRescueList)) {
                            scRescueList.forEach(scSeismicsetout -> {
                                Map<String, Object> staticsMap = new HashMap<>();
                                staticsMap.put("num", atomicInteger12.getAndAdd(1));
                                staticsMap.put("province", province);
                                staticsMap.put("city", city);
                                staticsMap.put("county", county);
                                staticsMap.put("name", scSeismicsetout.getScRescueName());
                                staticsMap.put("industry", scSeismicsetout.getScRescueIndustry());
                                staticsMap.put("unit", scSeismicsetout.getScRescueUnit());
                                staticsMap.put("address", scSeismicsetout.getScRescueAddress());
                                staticsMap.put("amount", scSeismicsetout.getScRescueNumber());
                                staticsMap.put("note", scSeismicsetout.getScRescueNote());
                                reportRescueList.add(staticsMap);
                            });
                        }
                        List<ScEquip> scEquipList = seismicSetoutRepository.getEquip(entity.getScId());
                        if (PlatformObjectUtils.isNotEmpty(scEquipList)) {
                            scEquipList.forEach(scSeismicsetout -> {
                                Map<String, Object> staticsMap = new HashMap<>();
                                staticsMap.put("num", atomicInteger13.getAndAdd(1));
                                staticsMap.put("province", province);
                                staticsMap.put("city", city);
                                staticsMap.put("county", county);
                                staticsMap.put("name", scSeismicsetout.getScEquipName());
                                staticsMap.put("amount", scSeismicsetout.getScEquipNumber());
                                staticsMap.put("note", scSeismicsetout.getScEquipNote());
                                reportEquipList.add(staticsMap);
                            });
                        }
                        List<ScSanctuary> scSanctuaryList = seismicSetoutRepository.getSc(entity.getScId());
                        if (PlatformObjectUtils.isNotEmpty(scSanctuaryList)) {
                            scSanctuaryList.forEach(scSeismicsetout -> {
                                Map<String, Object> staticsMap = new HashMap<>();
                                staticsMap.put("num", atomicInteger14.getAndAdd(1));
                                staticsMap.put("province", province);
                                staticsMap.put("city", city);
                                staticsMap.put("county", county);
                                staticsMap.put("amount", scSeismicsetout.getScSanctuaryNumber());
                                staticsMap.put("area", scSeismicsetout.getScSanctuaryArea());
                                staticsMap.put("capacity", scSeismicsetout.getScSanctuaryNumberpeople());
                                reportSanctuaryList.add(staticsMap);
                            });
                        }
                        List<ScMedical> scScMedicalList = seismicSetoutRepository.getMe(entity.getScId());
                        if (PlatformObjectUtils.isNotEmpty(scScMedicalList)) {
                            scScMedicalList.forEach(scSeismicsetout -> {
                                Map<String, Object> staticsMap = new HashMap<>();
                                staticsMap.put("num", atomicInteger15.getAndAdd(1));
                                staticsMap.put("province", province);
                                staticsMap.put("city", city);
                                staticsMap.put("county", county);
                                staticsMap.put("name", scSeismicsetout.getScMedicalName());
                                staticsMap.put("doctorAmount", scSeismicsetout.getScMedicalDoctor());
                                staticsMap.put("nurseAmount", scSeismicsetout.getScMedicalNurse());
                                staticsMap.put("note", scSeismicsetout.getScMedicalNote());
                                reportMedicalList.add(staticsMap);
                            });
                        }
                    });
                }
            }
        } else {
            msgDetail.append(",").append("获取不到抽样调查点信息");
        }
        List<Map<String, Object>> ypgRoadList = new ArrayList<>();
        List<String> typeList = new ArrayList<>();
        typeList.add("铁路");
        typeList.add("国道");
        typeList.add("省道");
        typeList.add("县道");
        typeList.add("隧道");
        typeList.add("桥梁");
        //表1.4 工作区交通概况统计表
        List<Road> finalList = new ArrayList<>();
        if (!isCounty) {
            allRoadList = allRoadList.stream().distinct().collect(Collectors.toList());
            if (allRoadList.size() > 0) {
                //获取任务区域内的数据
                if (subTask == null) {
                    subTask = new ArrayList<>();
                    //父任务
                    subTask.add(task);
                }
                for (PreAssessTaskEntity taskEntity : subTask) {
                    for (Road road : allRoadList) {
                        if (roadMapService.getRoadByTaskId(road.getGeomText(), taskEntity.getId())) {
                            finalList.add(road);
                        }
                    }
                }
            }
        } else {
            finalList = allRoadList;
        }


        for (Road road : finalList) {
            if ("国道".equals(road.getRoadType())) {
                gd.append(road.getRoadName()).append("、");
            }
            if ("省道".equals(road.getRoadType())) {
                sd.append(road.getRoadName()).append("、");
            }
            if ("县道".equals(road.getRoadType())) {
                xd.append(road.getRoadName()).append("、");
            }
            if ("桥".equals(road.getRoadType())) {
                ql.append(road.getRoadName()).append("、");
            }
        }
        for (int i = 0; i < typeList.size(); i++) {
            Map<String, Object> roadMap = new HashMap<>();
            roadMap.put("roadType", typeList.get(i));
            if (i == 0) {
                roadMap.put("roadName", "");
            }
            if (i == 1) {
                roadMap.put("roadName", StringUtils.isNotBlank(gd) ? (gd.substring(0, gd.length() - 1)) : "");
            }
            if (i == 2) {
                roadMap.put("roadName", StringUtils.isNotBlank(sd) ? (sd.substring(0, sd.length() - 1)) : "");
            }
            if (i == 3) {
                roadMap.put("roadName", StringUtils.isNotBlank(xd) ? (xd.substring(0, xd.length() - 1)) : "");
            }
            if (i == 4) {
                roadMap.put("roadName", "");
            }
            if (i == 5) {
                roadMap.put("roadName", StringUtils.isNotBlank(ql) ? (ql.substring(0, ql.length() - 1)) : "");
            }
            ypgRoadList.add(roadMap);
        }
        if (allGeoList.size() > 0) {
            Map<String, List<GeologicalEntity>> disasterCollect = allGeoList.stream().collect(Collectors.groupingBy(GeologicalEntity::getDgdDisasterType));
            disasterCollect.forEach((k, v) -> {
                disasterDetails.append(k).append("隐患点").append(v.size()).append("处").append("、");
            });
            if (disasterDetails.length() > 0) {
                ddTails = disasterDetails.substring(0, disasterDetails.length() - 1);
            }
            Map<String, Long> geoMap = allGeoList.stream().collect(Collectors.groupingBy(GeologicalEntity::getDgdDisasterType, Collectors.counting()));
            //取出map键值对Entry<K,V>，然后按照值排序，最后组成一个新的列表集合
            List<Map.Entry<String, Long>> list = geoMap.entrySet()
                    .stream()
                    //sorted((p2,p1)   表示由大到小排序   ||  sorted((p1,p2)   表示由小到大排序
                    .sorted((p2, p1) -> p1.getValue().compareTo(p2.getValue()))
                    .collect(Collectors.toList());
            master = list.get(0).getKey();
            if (list.size() > 1) {
                slave = list.get(1).getKey();
            }

            //影响人口数
//            int sum = PlatformObjectUtils.isNotEmpty(allGeoList) ? (allGeoList.stream().mapToInt(GeologicalEntity::getDgdImpactPeoNum).sum()) : 0;
            int sum = 0;
            List<GeologicalEntity> peoNumList = allGeoList.stream()
                    .filter(entity -> ObjectUtils.isEmpty(entity.getDgdImpactPeoNum())).collect(Collectors.toList());
            if(peoNumList.size() == allGeoList.size()){
                personNum = null;
            }else{
                sum = allGeoList.stream()
                        .filter(entity->ObjectUtils.isNotEmpty(entity.getDgdImpactPeoNum()))
                        .mapToInt(GeologicalEntity::getDgdImpactPeoNum)
                        .sum();
                personNum.getAndAdd(sum);
            }
            //影响房屋数
//            int hNum = PlatformObjectUtils.isNotEmpty(allGeoList) ? (allGeoList.stream().mapToInt(GeologicalEntity::getDgdImpactHouseNum).sum()) : 0;
            int hNum = 0;
            List<GeologicalEntity> houseNumList = allGeoList.stream()
                    .filter(entity -> ObjectUtils.isEmpty(entity.getDgdImpactHouseNum())).collect(Collectors.toList());
            if(houseNumList.size() == allGeoList.size()){
                houseNum = null;
            }else{
                hNum = allGeoList.stream()
                        .filter(entity->ObjectUtils.isNotEmpty(entity.getDgdImpactHouseNum()))
                        .mapToInt(GeologicalEntity::getDgdImpactHouseNum)
                        .sum();
                houseNum.getAndAdd(hNum);
            }

            if (PlatformObjectUtils.isNotEmpty(allGeoList)) {
                Map<String, List<GeologicalEntity>> levelMap = allGeoList.stream().collect(Collectors.groupingBy(GeologicalEntity::getDgdDangerLevel));
                levelMap.forEach((k, v) -> {
                    damageLevel.append(k).append(v.size()).append("处、");
                });
                Map<String, List<String>> seriousMap = new HashMap<>();
                //Map<String, String> mostMap = allGeoList.stream().filter(geologicalEntity -> "特大型".equals(geologicalEntity.getDgdDangerLevel()) ).collect(Collectors.toMap(GeologicalEntity::getDgdDangerLevel, GeologicalEntity::getDgdName));
                String substring = "";
                Iterator<Map.Entry<String, List<GeologicalEntity>>> iterator = levelMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, List<GeologicalEntity>> next = iterator.next();
                    String key = next.getKey();
                    if ("特大型".equals(key)) {
                        List<GeologicalEntity> value = next.getValue();
                        if (value.size() > 0) {
                            mostBuilder.append("有");
                            List<String> nameList = value.stream().map(GeologicalEntity::getDgdName).collect(Collectors.toList());
                            mostBuilder.append(String.join("、", nameList));
                            substring = mostBuilder.toString();
                        } else {
                            substring = "无";
                        }
                    } else {
                        substring = "无";
                    }
                    if ("大型".equals(key)) {
                        List<GeologicalEntity> value = next.getValue();
                        List<String> nameList = value.stream().map(GeologicalEntity::getDgdName).collect(Collectors.toList());
                        if (seriousMap.containsKey(key)) {
                            List<String> strings = seriousMap.get(key);
                            strings.addAll(nameList);
                            seriousMap.put(key, strings);
                        } else {
                            List<String> strings = new ArrayList<>();
                            strings.addAll(nameList);
                            seriousMap.put(key, strings);
                        }
                    }
                }

                //Map<String, String> seriousMap = allGeoList.stream().filter(geologicalEntity -> "大型".equals(geologicalEntity.getDgdDangerLevel()) ).collect(Collectors.toMap(GeologicalEntity::getDgdDangerLevel, GeologicalEntity::getDgdName));
                StringBuilder seriousBuilder = new StringBuilder();
                String seriousDetails = "";
                if (!"".equals(substring)) {
                    seriousBuilder.append(substring).append(";险情等级为大型的隐患点");
                }
                if (seriousMap.values().size() > 0) {
                    seriousBuilder.append("有");
                    seriousMap.forEach((k, v) -> {
                        //seriousBuilder.append(v).append("、");
                        seriousBuilder.append(String.join("、", v));
                    });
                    //seriousDetails = seriousBuilder.substring(0, seriousBuilder.length() - 1);
                    seriousDetails = seriousBuilder.toString();
                } else {
                    seriousBuilder.append("无");
                    seriousDetails = seriousBuilder.toString();
                }
                damageLevelDetails = damageLevelDetails.append(seriousDetails);
            }
        }
        //水库
        StringBuilder reservorDetails = new StringBuilder();
        if (reservorSet.size() > 0) {
            reservorSet.forEach(str -> {
                reservorDetails.append(str).append("、");
            });
        }
        String reStr = "";
        if (reservorDetails.length() > 0) {
            reStr = reservorDetails.substring(0, reservorDetails.length() - 1);
        }

        StringBuilder schoolDetails = new StringBuilder();
        if (schoolSet.size() > 0) {
            schoolSet.forEach(str -> {
                schoolDetails.append(str).append("、");
            });
        }
        String shStr = "";
        if (schoolDetails.length() > 0) {
            shStr = schoolDetails.substring(0, schoolDetails.length() - 1);
        }
        //--------第一章结束
        //--------第二章开始
        //构建调研点信息表
        Map<String, Object> tatalMap = buildSurveyMessage(samplingList, taskCode, msgDetail);
        List<Map<String, Object>> samplingInfoList = (List<Map<String, Object>>) tatalMap.get("samplingInfoList");
        List<SamplingArea> surveyList = (List<SamplingArea>) tatalMap.get("areaList2");
        List<SamplingArea> surveyList3 = (List<SamplingArea>) tatalMap.get("areaList3");

        List<Map<String, Object>> reportTrafficAnalyseList = new ArrayList<>();
        List<Map<String, Object>> reportTrafficAnalyseList7 = new ArrayList<>();
        List<Map<String, Object>> reportTrafficAnalyseList8 = new ArrayList<>();
        List<Map<String, Object>> reportTrafficAnalyseList9 = new ArrayList<>();
        List<Map<String, Object>> reportTrafficAnalyseList10 = new ArrayList<>();
        List<Map<String, Object>> reportTrafficAnalyseList11 = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(ypgResultRoadList)) {
            ypgResultRoadList.forEach(resultRoad -> {
                Map<String, Object> reloadMap = new HashMap<>();
                reloadMap.put("roadType", resultRoad.getRoadType());
                reloadMap.put("roadName", resultRoad.getRoadName());
                if ("6".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList.add(reloadMap);
                } else if ("7".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList7.add(reloadMap);
                } else if ("8".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList8.add(reloadMap);
                } else if ("9".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList9.add(reloadMap);
                } else if ("10".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList10.add(reloadMap);
                } else if ("11".equals(resultRoad.getDzIntensity())) {
                    reportTrafficAnalyseList11.add(reloadMap);
                }
            });
        } else {
            reportTrafficAnalyseList.add(new HashMap<>());
            reportTrafficAnalyseList7.add(new HashMap<>());
            reportTrafficAnalyseList8.add(new HashMap<>());
            reportTrafficAnalyseList9.add(new HashMap<>());
            reportTrafficAnalyseList10.add(new HashMap<>());
            reportTrafficAnalyseList11.add(new HashMap<>());
        }
        List<Map<String, Object>> reportRiskEnterpriseList = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(riskEnterpriseData)) {
            AtomicInteger riskNum = new AtomicInteger(1);
            riskEnterpriseData.forEach(entity -> {
                Map<String, Object> riskMap = new HashMap<>();
                riskMap.put("num", riskNum.getAndIncrement());
                riskMap.put("province", entity.getProvince());
                riskMap.put("city", entity.getCity());
                riskMap.put("county", entity.getCounty());
                riskMap.put("name", entity.getRedName());
                riskMap.put("address", entity.getRedAddress());
                riskMap.put("type", entity.getRedType());
                riskMap.put("level", entity.getRedRiskgrade());
                reportRiskEnterpriseList.add(riskMap);
            });
        } else {
            reportRiskEnterpriseList.add(new HashMap<>());
        }

        List<Map<String, Object>> reportGasList = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(gassData)) {
            AtomicInteger gasNum = new AtomicInteger(1);
            gassData.forEach(entity -> {
                Map<String, Object> gasMap = new HashMap<>();
                gasMap.put("num", gasNum.getAndIncrement());
                gasMap.put("province", entity.getProvince());
                gasMap.put("city", entity.getCity());
                gasMap.put("county", entity.getCounty());
                gasMap.put("name", entity.getGsName());
                gasMap.put("address", entity.getGsAddress());
                gasMap.put("scale", entity.getGsScale());
                gasMap.put("level", entity.getGsRiskgrade());
                reportGasList.add(gasMap);
            });
        } else {
            reportGasList.add(new HashMap<>());
        }
        Map<String, Object> reportData = null;
        try {
            reportData = reportDataService.getReportData(taskId, taskIdList, msgDetail);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Object magnitudes = reportData.get("magnitudes");
        Object earthSum = reportData.get("earthSum");
        Object deathNumber = reportData.get("deathNumber");
        Object injuries = reportData.get("injuries");
        Object structureLossess = reportData.get("structureLossess");
        Object indoorLossess = reportData.get("indoorLossess");
        Object liferatioBm = reportData.get("liferatioBm");
        Object liferatioLm = reportData.get("liferatioLm");
        Object otherRatioBm = reportData.get("otherRatioBm");
        Object otherRatioOm = reportData.get("otherRatioOm");
        Object modelNumber1 = reportData.get("modelNumber1");
        Object modelNumber2 = reportData.get("modelNumber2");
        Object modelNumber3 = reportData.get("modelNumber3");
        Object modelNumber4 = reportData.get("modelNumber4");
        Object modelNumber5 = reportData.get("modelNumber5");
        Object modelNumber6 = reportData.get("modelNumber6");
        Object modelNumber7 = reportData.get("modelNumber7");
        Object modelNumber8 = reportData.get("modelNumber8");
        Object modelNumber9 = reportData.get("modelNumber9");
        Object modelNumber10 = reportData.get("modelNumber10");
        Object modelNumber11 = reportData.get("modelNumber11");
        Object modelNumber12 = reportData.get("modelNumber12");
        Object modelNumber13 = reportData.get("modelNumber13");
        Object modelNumber14 = reportData.get("modelNumber14");
        Object modelNumber15 = reportData.get("modelNumber15");
        Object modelNumber16 = reportData.get("modelNumber16");
        Object modelNumber17 = reportData.get("modelNumber17");
        Object modelNumber18 = reportData.get("modelNumber18");
        Object modelNumber19 = reportData.get("modelNumber19");
        Object modelNumber20 = reportData.get("modelNumber20");
        Object modelNumber21 = reportData.get("modelNumber21");
        Object modelNumber22 = reportData.get("modelNumber22");
        Object intensity = reportData.get("intensity");
        Object earthtable = reportData.get("earthtable");
        Object destorytable = reportData.get("destorytable");
        Object resultTable1 = reportData.get("resultTable");
        Object tabless = reportData.get("tables");
        List<ResultTable> tables = null;
        if (PlatformObjectUtils.isNotEmpty(tabless)) {
            tables = (List<ResultTable>) tabless;
        }
        List<Injured> injureds = new ArrayList<>();
        List<Resettled> resettleds = new ArrayList<>();
        List<Rescue> rescues = new ArrayList<>();
        Map<String, Map<String, List<Object[]>>> areaResultList = reportDataService.getAreaResultList(taskId, level, taskIdList);
        Map<String, List<Object[]>> stringListMap1 = areaResultList.get("1");
        Map<String, List<Object[]>> stringListMap2 = areaResultList.get("2");
        Map<String, List<Object[]>> stringListMap3 = areaResultList.get("3");
//        if ("1".equals(level)){
        Set<String> strings1 = stringListMap1.keySet();
        if (strings1.size() > 0) {
            int i = 1;
            for (String string : strings1) {
                Injured injured = new Injured();
                injured.setCountyTitle1("3.3." + i + string + "预评估结果");
                List<Object[]> string1 = stringListMap1.get(string);
                StringBuilder stringBuilder = new StringBuilder();
                int a = 0;
                for (Object[] objects : string1) {
                    a++;
//                        if (objects[1].toString().contains("-0")){
//                            objects[1]=objects[1].toString().split("-")[0];
//                        }
//                        if (PlatformObjectUtils.isNotEmpty(objects[2]) && objects[2].toString().contains("-0")){
//                            objects[2]=objects[2].toString().split("-")[0];
//                        }else{
//                            objects[2] = "";
//                        }
                    if (a == 1) {
                        stringBuilder.append(objects[0]).append(" 级地震：死亡人数：").append(objects[1]).append(" 人；受伤人数：").append(objects[2]).append("人");
                        stringBuilder.append("\n");
                    } else {
                        stringBuilder.append("    " + objects[0] + " 级地震：死亡人数：" + objects[1] + " 人");
                        if (PlatformObjectUtils.isNotEmpty(objects[2])) {
                            stringBuilder.append("；受伤人数：").append(objects[2]).append("人");
                        }
                        stringBuilder.append("\n");
                    }
                }
                injured.setContent1(stringBuilder.toString());
                injureds.add(injured);
                i++;
            }
        }
        Set<String> strings2 = stringListMap2.keySet();
        if (strings2.size() > 0) {
            int i = 1;
            for (String string : strings2) {
                Resettled resettled = new Resettled();
                resettled.setCountyTitle2(("3.4." + i + string + "预评估结果"));
                List<Object[]> string2 = stringListMap2.get(string);
                StringBuilder stringBuilder = new StringBuilder();
                int a = 0;
                for (Object[] objects : string2) {
                    a++;
//                        if (objects[1].toString().contains("-0")){
//                            objects[1]=objects[1].toString().split("-")[0];
//                        }
                    if (a == 1) {
                        stringBuilder.append(objects[0] + " 级地震：需紧急安置人数：" + objects[1] + "人" + "\n");
                    } else {
                        stringBuilder.append("    " + objects[0] + " 级地震：需紧急安置人数：" + objects[1] + "人" + "\n");
                    }
                }
                resettled.setContent2(stringBuilder.toString());
                resettleds.add(resettled);
                i++;
            }
        }
        Set<String> strings3 = stringListMap3.keySet();
        if (strings3.size() > 0) {
            int i = 1;
            for (String string : strings3) {
                Rescue rescue = new Rescue();
                rescue.setCountyTitle3("3.5." + i + string + "预评估结果");
                List<Object[]> string3 = stringListMap3.get(string);
                StringBuilder stringBuilder = new StringBuilder();
                int a = 0;
                for (Object[] objects : string3) {
                    a++;
//                        if (objects[1].toString().contains("-0")){
//                            objects[1]=objects[1].toString().split("-")[0];
//                        }
//                        if (PlatformObjectUtils.isNotEmpty(objects[2]) && objects[2].toString().contains("-0")){
//                            objects[2]=objects[2].toString().split("-")[0];
//                        }else{
//                            objects[2]= "";
//                        }
                    if (a == 1) {
                        stringBuilder.append(objects[0] + " 级地震：需紧急救援力量：" + objects[1] + " 人");
                        if (PlatformObjectUtils.isNotEmpty(objects[2])) {
                            stringBuilder.append("；需帐篷：").append(objects[2]).append("顶").append("\n");
                        }
                    } else {
                        stringBuilder.append("    " + objects[0] + " 级地震：需紧急救援力量：" + objects[1] + " 人");
                        if (PlatformObjectUtils.isNotEmpty(objects[2])) {
                            stringBuilder.append("；需帐篷：").append(objects[2]).append("顶").append("\n");
                        }
                    }
                }
                rescue.setContent3(stringBuilder.toString());
                rescues.add(rescue);
                i++;
            }
        }

//        }
        //Object resettle1 = reportData.get("resettle1");
        //Object resettle = reportData.get("resettle");
        Object modelName1 = reportData.get("modelName1");
        Object modelName2 = reportData.get("modelName2");
        Object ratio = reportData.get("ratio");
        //Object resettle3 = reportData.get("resettle3");
//        List<Map<String, PictureRenderData>> resettle2 = new ArrayList<>(1);
//        Map<String, PictureRenderData> picMap = new HashMap<>();
//        //picMap.put("pictures", new PictureRenderData(150, 40, "D:\\static\\图片1.png"));
//        picMap.put("pictures", null);
//        if (PlatformObjectUtils.isNotEmpty(resettle) && "1".equals(resettle.toString())){
//            resettle2.add(picMap);
//        }
        List<Map<String, Object>> resettle4 = new ArrayList<>();
//        TableRenderData table = Tables.create();
        if (PlatformObjectUtils.isNotEmpty(ratio)) {
            List<YpgRatio> ratioList = (List<YpgRatio>) ratio;
            for (YpgRatio ypgRatio : ratioList) {
                Map<String, Object> map = new HashMap<>();
                map.put("intensity", ypgRatio.getIntensity());
                map.put("province", ypgRatio.getProvince());
                map.put("resettlementRatio1", ypgRatio.getResettlementRatio1());
                map.put("resettlementRatio2", ypgRatio.getResettlementRatio2());
                map.put("resettlementRatio3", ypgRatio.getResettlementRatio3());
                map.put("resettlementRatio4", ypgRatio.getResettlementRatio4());
                resettle4.add(map);
            }
//            RowRenderData row0 = Rows.of("烈度","省", "Ⅵ", "Ⅶ", "Ⅷ", ">Ⅸ").center().create();
//            RowRenderData row1 = Rows.of("需紧急安置人数占人口比例", ratioList.get(0),ratioList.get(1)+"", ratioList.get(2)+"", ratioList.get(3)+"", ratioList.get(4)+"").center().create();
//            table = Tables.create(row0,row1);
        }

        //7-8章对策建议分析
        Map<String, Object> suggestMap = getSuggestion(task, level, voList, msgDetail);
        List<Suggestion> disasterSuggestList = (List<Suggestion>) suggestMap.get("disasterSuggestList");
        List<Preparedness> preparednessList = (List<Preparedness>) suggestMap.get("preparednessList");
        List<Disposal> disposalList = (List<Disposal>) suggestMap.get("disposalList");
        String tempPic = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("1", "临时名称") : "";
        PictureRenderData popPicture = null;
        if (StringUtils.isNotBlank(tempPic)) {
            popPicture = new PictureRenderData(500, 300, tempPic);
        }
        tempPic = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("2", "临时名称") : "";
        PictureRenderData gdpPicture = null;
        if (StringUtils.isNotBlank(tempPic)) {
            gdpPicture = new PictureRenderData(500, 300, tempPic);
        }
        Map<String, String> row9 = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.row("9") : null;
        if (PlatformObjectUtils.isEmpty(row9)) {
            row9 = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.row("10") : null;
            if (PlatformObjectUtils.isEmpty(row9)) {
                row9 = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.row("11") : null;
            }
        }
        List<Map<String, PictureRenderData>> seismicResistancePic = new ArrayList<>();
        //PictureRenderData seismicResistancePic = null;
        if (PlatformObjectUtils.isNotEmpty(row9)) {
            row9.forEach((k, v) -> {
                HashMap<String, PictureRenderData> seismicResistanceMap = new HashMap<>();
                seismicResistanceMap.put("picture", new PictureRenderData(500, 300, v));
                seismicResistancePic.add(seismicResistanceMap);
            });
            //seismicResistancePic = new PictureRenderData(500, 300, tempPic);
        }
        tempPic = PlatformObjectUtils.isNotEmpty(pathMap) ? pathMap.get("6", "临时名称") : "";
        PictureRenderData earthCenterImage = null;
        if (StringUtils.isNotBlank(tempPic)) {
            earthCenterImage = new PictureRenderData(500, 300, tempPic);
        }
        YpgReport report = YpgReport.builder().areaList(new ArrayList<>())
                .resultTable1(tables)
                .intensity(PlatformObjectUtils.isNotEmpty(intensity) ? intensity.toString() : "")
                .modelName1(PlatformObjectUtils.isNotEmpty(modelName1) ? modelName1.toString() : "")
                .modelName2(PlatformObjectUtils.isNotEmpty(modelName2) ? modelName2.toString() : "")
                //.resettle1(PlatformObjectUtils.isNotEmpty(resettle1)?resettle1.toString():"")
                //.resettle2(resettle2)
                //.resettle3(PlatformObjectUtils.isNotEmpty(resettle3)?resettle3.toString():"")
                .resettle4(resettle4)
                .countyList3(rescues)
                .countyList2(resettleds)
                .countyList1(injureds)
                .areaList1(new ArrayList<>())
                .populationList(new ArrayList<>())
                .populationDetails(new ArrayList<>())
                .popPicture(popPicture)
                .gdpPicture(gdpPicture)
                .economyList(new ArrayList<>())
                .buildingFuture(new ArrayList<>())
                .seismicResistancePic(new ArrayList<>())
                .evaluationList(new ArrayList<>())
                .trafficList(new ArrayList<>())
                .trafficImage(trafficImage)
                .roadList(ypgRoadList)
                .reservoirNum(reservoNum + "")
                .reservorDetails(reStr)
                .reservoirImage(new ArrayList<>())
                .reservoirList(reportReservoirList)
                .schoolNum(schNum + "")
                .schoolDetails(shStr)
                .schoolImage(new ArrayList<>())
                .schoolList(reportSchoolList)
                .disasterNum(disasterNum.get() + "")
                .master(master)
                .slave(slave)
                .disasterDetails(ddTails)
                .personNum(personNum == null ? " " : personNum.get() + "")
                .houseNum(houseNum == null ? " ":houseNum.get() + "")
                .damageLevel(StringUtils.isNotBlank(damageLevel) ? damageLevel.substring(0, damageLevel.length() - 1) : "")
                .damageLevelDetails(StringUtils.isNotBlank(damageLevelDetails) ? damageLevelDetails.toString() : "")
                .disasterList(reportDisasterList)
                .disasterPointImage(new ArrayList<>())
                .earthFutureeList(new ArrayList<>())
                .historyFutureeList(new ArrayList<>())
                .samplingInfoList(samplingInfoList)
                .samplingPointImage(new ArrayList<>())
                .areaList2(surveyList)
                .areaList3(surveyList3)
                .riskImage(new ArrayList<>())
                .trafficAnalyse(tanalysis == null ? "" : tanalysis.getTrafficAnalysis())
                .trafficAnalyseList(reportTrafficAnalyseList)
                .trafficAnalyseList7(reportTrafficAnalyseList7)
                .trafficAnalyseList8(reportTrafficAnalyseList8)
                .trafficAnalyseList9(reportTrafficAnalyseList9)
                .trafficAnalyseList10(reportTrafficAnalyseList10)
                .trafficAnalyseList11(reportTrafficAnalyseList11)
                .trafficAnalyseImage(new ArrayList<>())
                .riskEnterpriseList(reportRiskEnterpriseList)
                .gasList(reportGasList)
                .planSystemList(reportPlanSystemList)
                .mechanismList(reportMechanismList)
                .implementationList(reportImplementationList)
                .safeguardsList(reportSafeguardsList)
                .preventionList(reportPreventionList)
                .medicalhelpList(reportMedicalhelpList)
                .demandList(reportDemandList)
                .developmentList(reportDevelopmentList)
                .supportabilityList(reportSupportabilityList)
                .publicOpinionList(reportPublicOpinionList)
                .scienceList(reportScienceList)
                .otherList(reportOtherList)
                .reservesList(reportReservesList)
                .rescueList(reportRescueList)
                .equipList(reportEquipList)
                .sanctuaryList(reportSanctuaryList)
                .medicalList(reportMedicalList)
                .modelNumber1(PlatformObjectUtils.isNotEmpty(modelNumber1) ? modelNumber1.toString() : "")
                .magnitudes(PlatformObjectUtils.isNotEmpty(magnitudes) ? magnitudes.toString() : "")
                .earthSum(PlatformObjectUtils.isNotEmpty(earthSum) ? earthSum.toString() : "")
                .earthCenterImage(earthCenterImage)
                .deathNumber(PlatformObjectUtils.isNotEmpty(deathNumber) ? deathNumber.toString() : "")
                .injuries(PlatformObjectUtils.isNotEmpty(injuries) ? injuries.toString() : "")
                .structureLossess(PlatformObjectUtils.isNotEmpty(structureLossess) ? structureLossess.toString() : "")
                .indoorLossess(PlatformObjectUtils.isNotEmpty(indoorLossess) ? indoorLossess.toString() : "")
                .liferatioBm(PlatformObjectUtils.isNotEmpty(liferatioBm) ? liferatioBm.toString() : "")
                .liferatioLm(PlatformObjectUtils.isNotEmpty(liferatioLm) ? liferatioLm.toString() : "")
                .otherRatioBm(PlatformObjectUtils.isNotEmpty(otherRatioBm) ? otherRatioBm.toString() : "")
                .otherRatioOm(PlatformObjectUtils.isNotEmpty(otherRatioOm) ? otherRatioOm.toString() : "")
                .modelNumber1(PlatformObjectUtils.isNotEmpty(modelNumber1) ? modelNumber1.toString() : "")
                .modelNumber2(PlatformObjectUtils.isNotEmpty(modelNumber2) ? modelNumber2.toString() : "")
                .modelNumber3(PlatformObjectUtils.isNotEmpty(modelNumber3) ? modelNumber3.toString() : "")
                .modelNumber4(PlatformObjectUtils.isNotEmpty(modelNumber4) ? modelNumber4.toString() : "")
                .modelNumber5(PlatformObjectUtils.isNotEmpty(modelNumber5) ? modelNumber5.toString() : "")
                .modelNumber6(PlatformObjectUtils.isNotEmpty(modelNumber6) ? modelNumber6.toString() : "")
                .modelNumber7(PlatformObjectUtils.isNotEmpty(modelNumber7) ? modelNumber7.toString() : "")
                .modelNumber8(PlatformObjectUtils.isNotEmpty(modelNumber8) ? modelNumber8.toString() : "")
                .modelNumber9(PlatformObjectUtils.isNotEmpty(modelNumber9) ? modelNumber9.toString() : "")
                .modelNumber10(PlatformObjectUtils.isNotEmpty(modelNumber10) ? modelNumber10.toString() : "")
                .modelNumber11(PlatformObjectUtils.isNotEmpty(modelNumber11) ? modelNumber11.toString() : "")
                .modelNumber12(PlatformObjectUtils.isNotEmpty(modelNumber12) ? modelNumber12.toString() : "")
                .modelNumber13(PlatformObjectUtils.isNotEmpty(modelNumber13) ? modelNumber13.toString() : "")
                .modelNumber14(PlatformObjectUtils.isNotEmpty(modelNumber14) ? modelNumber14.toString() : "")
                .modelNumber15(PlatformObjectUtils.isNotEmpty(modelNumber15) ? modelNumber15.toString() : "")
                .modelNumber16(PlatformObjectUtils.isNotEmpty(modelNumber16) ? modelNumber16.toString() : "")
                .modelNumber17(PlatformObjectUtils.isNotEmpty(modelNumber17) ? modelNumber17.toString() : "")
                .modelNumber18(PlatformObjectUtils.isNotEmpty(modelNumber18) ? modelNumber18.toString() : "")
                .modelNumber19(PlatformObjectUtils.isNotEmpty(modelNumber19) ? modelNumber19.toString() : "")
                .modelNumber20(PlatformObjectUtils.isNotEmpty(modelNumber20) ? modelNumber20.toString() : "")
                .modelNumber21(PlatformObjectUtils.isNotEmpty(modelNumber21) ? modelNumber21.toString() : "")
                .modelNumber22(PlatformObjectUtils.isNotEmpty(modelNumber22) ? modelNumber22.toString() : "")
                .earthtable(new ArrayList<>())
                .destorytable(new ArrayList<>())
                .disasterSuggestList(disasterSuggestList)
                .preparednessList(preparednessList)
                .disposalList(disposalList)
                .build();
        List<YpgArea> reportAreaList = report.getAreaList();
        List<YpgArea1> reportAreaList1 = report.getAreaList1();
        List<Map<String, Object>> populationList = report.getPopulationList();
        List<PopulationDetails> detailsList = report.getPopulationDetails();

        List<Map<String, Object>> ecoList = report.getEconomyList();
        List<YpgArea2> bfList = report.getBuildingFuture();
        List<Map<String, Object>> evaluationList = report.getEvaluationList();
        List<Traffic> trafficList = report.getTrafficList();
        List<Earthquake> earthFutureeList = report.getEarthFutureeList();
        List<Earthquake> historyFutureeList = report.getHistoryFutureeList();
        List<Map<String, Object>> earthtable1 = report.getEarthtable();
        List<Map<String, Object>> destorytable1 = report.getDestorytable();
        //水库分布图
        List<Map<String, PictureRenderData>> reservoirImage = report.getReservoirImage();
        HashMap<String, PictureRenderData> reservoirImageMap = new HashMap<>();

        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("18", "临时名称"))) {
            reservoirImageMap.put("picture", new PictureRenderData(500, 300, pathMap.get("18", "临时名称")));
        } else {
            reservoirImageMap.put("picture", null);
        }
        reservoirImage.add(reservoirImageMap);
        List<Map<String, PictureRenderData>> seismicResistancePicList = report.getSeismicResistancePic();
        seismicResistancePicList.addAll(seismicResistancePic);
        //学校分布图
        List<Map<String, PictureRenderData>> schoolImage = report.getSchoolImage();
        HashMap<String, PictureRenderData> schoolImageMap = new HashMap<>();
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("12", "临时名称"))) {
            schoolImageMap.put("picture", new PictureRenderData(500, 300, pathMap.get("12", "临时名称")));
        } else {
            schoolImageMap.put("picture", null);
        }
        schoolImage.add(schoolImageMap);
        //地质灾害隐患点分布图
        List<Map<String, PictureRenderData>> disasterPointImage = report.getDisasterPointImage();
        HashMap<String, PictureRenderData> disasterPointMap = new HashMap<>();
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("7", "临时名称"))) {
            disasterPointMap.put("picture", new PictureRenderData(500, 300, pathMap.get("7", "临时名称")));
        } else {
            disasterPointMap.put("picture", null);
        }
        disasterPointImage.add(disasterPointMap);
        //调研点分布图
        List<Map<String, PictureRenderData>> samplingPointImage = report.getSamplingPointImage();
        HashMap<String, PictureRenderData> samplingPointMap = new HashMap<>();
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("14", "临时名称"))) {
            samplingPointMap.put("picture", new PictureRenderData(500, 300, pathMap.get("14", "临时名称")));
        } else {
            samplingPointMap.put("picture", null);
        }

        samplingPointImage.add(samplingPointMap);
        //遭遇烈度 VI 度地震地质灾害风险分布图
        //List<Map<String,PictureRenderData>> riskImage = new ArrayList<>();
        List<ImageData> riskImage = report.getRiskImage();
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.row("15"))) {
            Map<String, String> row15 = pathMap.row("15");
            if (PlatformObjectUtils.isNotEmpty(row15)) {
                final AtomicInteger[] atomicInteger = {new AtomicInteger(1)};
                row15.forEach((k, v) -> {
                    ImageData imageData = new ImageData();
                    List<Map<String, PictureRenderData>> list = new ArrayList<>();
                    HashMap<String, PictureRenderData> riskMap = new HashMap<>();
                    riskMap.put("picture", new PictureRenderData(500, 300, v));
                    list.add(riskMap);
                    imageData.setPicImage(list);
                    imageData.setTitle("图 4." + atomicInteger[0].get() + " " + k);
                    atomicInteger[0].getAndAdd(1);
                    riskImage.add(imageData);
                });
            }
        } else {
            ImageData imageData = new ImageData();
            List<Map<String, PictureRenderData>> list = new ArrayList<>();
            HashMap<String, PictureRenderData> riskMap = new HashMap<>();
            riskMap.put("picture", null);
            list.add(riskMap);
            imageData.setPicImage(list);
            riskImage.add(imageData);
        }
        //遭遇烈度Ⅵ度时交通受损情况分布图
        //List<Map<String,PictureRenderData>> trafficAnalyseImage = report.getTrafficAnalyseImage();
        List<ImageData> trafficAnalyseImage = report.getTrafficAnalyseImage();
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.row("16"))) {
            Map<String, String> row16 = pathMap.row("16");
            if (PlatformObjectUtils.isNotEmpty(row16)) {
                final AtomicInteger[] atomicInteger = {new AtomicInteger(1)};
                row16.forEach((k, v) -> {
                    ImageData imageData = new ImageData();
                    List<Map<String, PictureRenderData>> list = new ArrayList<>();
                    HashMap<String, PictureRenderData> trafficAnalyseMap = new HashMap<>();
                    trafficAnalyseMap.put("picture", new PictureRenderData(500, 300, v));
                    list.add(trafficAnalyseMap);
                    imageData.setPicImage(list);
                    imageData.setTitle("图 5." + atomicInteger[0].get() + " " + k);
                    atomicInteger[0].getAndAdd(1);
                    trafficAnalyseImage.add(imageData);
                });
            }
//            HashMap<String, PictureRenderData> trafficAnalyseMap = new HashMap<>();
//            trafficAnalyseMap.put("picture",new PictureRenderData(500, 300, pathMap.get("16")));
//            trafficAnalyseImage.add(trafficAnalyseMap);
        } else {
            ImageData imageData = new ImageData();
            List<Map<String, PictureRenderData>> list = new ArrayList<>();
            HashMap<String, PictureRenderData> trafficAnalyseMap = new HashMap<>();
            trafficAnalyseMap.put("picture", null);
            list.add(trafficAnalyseMap);
            imageData.setPicImage(list);
            trafficAnalyseImage.add(imageData);
        }

        earthtable1.addAll(earthtable != null ? ((List<Map<String, Object>>) earthtable) : new ArrayList<>());
        destorytable1.addAll(destorytable != null ? ((List<Map<String, Object>>) destorytable) : new ArrayList<>());
        reportAreaList.addAll(areaList);
        reportAreaList1.addAll(areaList1);
        populationList.addAll(popList);
        detailsList.addAll(populationDetailsList);
        ecoList.addAll(economyList);
        bfList.addAll(areaList2);
        evaluationList.addAll(reportEvaluationList);
        trafficList.addAll(reportTrafficList);
        earthFutureeList.addAll(hfutureeList);
        historyFutureeList.addAll(historyEarthList);
        reportList.add(report);
        Map<String, Object> paramMap = null;
        try {
            paramMap = reportDataService.getReportData(taskId, taskIdList, msgDetail);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        paramMap.put("year", year + "");
        paramMap.put("taskName", taskName);
        paramMap.put("createTime", sdf.format(date));
        paramMap.put("area", task.getTaskArea());
        paramMap.put("cityMsg", cityDetails);
        paramMap.put("cityMsgDetails", countyDetails);
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("0", "临时名称"))) {
            paramMap.put("administrativeImage", new PictureRenderData(500, 300, pathMap.get("0", "临时名称")));
        } else {
            paramMap.put("administrativeImage", null);
        }
        if (PlatformObjectUtils.isNotEmpty(pathMap) && PlatformObjectUtils.isNotEmpty(pathMap.get("3", "临时名称"))) {
            paramMap.put("landFormImage", new PictureRenderData(500, 300, pathMap.get("3", "临时名称")));
        } else {
            paramMap.put("landFormImage", null);
        }
        paramMap.put("townNum", townNum.toString());
        paramMap.put("townMsgDetails", townMsgDetails);
        paramMap.put("distirctPic", distirctPic);
        paramMap.put("dxPic", dxPic);
        //paramMap.put("disaterDamagePicture",disaterDamagePicture);
        paramMap.put("section1", reportList);
        // 生成文件
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(attachId);
        String fileDirId = attach.getFileDirId();
        String attachPath = attach.getAttachPath();
        Map<String, String> resultMap = createReport(paramMap, modelName, attachPath, fileDirId);
        //--生成报告逻辑结束
        FieldReportManagement rp = new FieldReportManagement();
        //保存或更新详本报告信息
        //生成的详本文件的名字
        String defaultMinuteReportName = (String) resultMap.get("docxName");
        ReportManagement newReport = reportManagementRepository.getReportByTaskId(taskId);
        ReportManagement reportManagement = new ReportManagement();
        String reportId = "";
        if (PlatformObjectUtils.isNotEmpty(newReport.getId())) {
            //该任务已经存在过报告附件则更新 否则新增
            reportId = newReport.getId();
            reportManagement.setId(newReport.getId());
            reportManagement.setDefaultMinuteReportName(defaultMinuteReportName);
            reportManagement.setDeReportTemplate(modelName);
            reportManagement.setDataSource("2");
            reportManagementRepository.update(reportManagement);
        } else {
            //新增报告附件
            reportId = UUIDGenerator.getUUID();
            preAssessTaskRepository.insertReportId(taskId, reportId);
            reportManagement.setId(reportId);
            reportManagement.setReportStatus("1");
            reportManagement.setDefaultMinuteReportName(defaultMinuteReportName);
            reportManagement.setReportCreateUserId(PlatformSessionContext.getUserID());
            //reportManagement.setReportCreateUserId("123");
            reportManagement.setReportCreateTime(new Date());
            reportManagement.setAdministrativeLevel(level);
            reportManagement.setReportPath(localDir);
            reportManagement.setDataSource("2");
            reportManagement.setDeReportTemplate(modelName);
            reportManagementRepository.save(reportManagement);
        }
        ReportManagement reportById = reportManagementRepository.getReportById(reportId);
        Map<String, Object> finalMap = new HashMap<>();
        finalMap.put("result", reportById);
        if (StringUtils.isNotBlank(msgDetail)) {
            char c = msgDetail.toString().charAt(0);
            if (c == ',') {
                finalMap.put("msg", msgDetail.substring(1, msgDetail.length() - 1));
            } else {
                finalMap.put("msg", msgDetail.toString());
            }
        } else {
            finalMap.put("msg", "");
        }

        //同步产品服务
        transReportMsgToCpxx(localDir+File.separator+defaultMinuteReportName,defaultMinuteReportName,taskName+","+"详本");
        return ResponseCreator.createSuccessResponse(finalMap);
    }


    private BiMap<String, String> getStructureMap() {
        BiMap<String, String> map = HashBiMap.create();
        map.put("高层结构", "0");
        map.put("钢结构-", "1");
        map.put("钢筋混凝土结构", "2");
        map.put("砖混结构", "3");
        map.put("砖木结构", "4");
        map.put("土结构", "5");
        map.put("木结构", "6");
        map.put("石结构", "7");
        map.put("其他结构", "8");
        return map;
    }

    private Map<String, Object> buildSurveyMessage(List<SamplingEntity> samplingList, String taskCode, StringBuilder msgDetail) {
        Map<String, List<SamplingEntity>> streetMap = new HashMap<>();
        Map<String, List<SamplingEntity>> villageMap = new HashMap<>();
        for (SamplingEntity samplingEntity : samplingList) {
            if (streetMap.containsKey(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea())) {
                List<SamplingEntity> streetList = streetMap.get(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea());
                streetList.add(samplingEntity);
            } else {
                List<SamplingEntity> steetList = new ArrayList<>();
                steetList.add(samplingEntity);
                streetMap.put(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea(), steetList);
            }
            if (villageMap.containsKey(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea() + "_" + samplingEntity.getTownship())) {
                List<SamplingEntity> surveyList = villageMap.get(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea() + "_" + samplingEntity.getTownship());
                surveyList.add(samplingEntity);
            } else {
                List<SamplingEntity> surveyList = new ArrayList<>();
                surveyList.add(samplingEntity);
                villageMap.put(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea() + "_" + samplingEntity.getTownship(), surveyList);
            }
        }
        Map<String, Object> tatalMap = new HashMap<>();
        List<SamplingArea> areaList = new ArrayList<>();
        List<SamplingArea2> areaList2 = new ArrayList<>();
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> distirctList = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(samplingList)) {
            samplingList.forEach(entity -> {
                String province = entity.getProvince();
                String city = entity.getCity();
                String county = entity.getArea();
                if (!distirctList.contains(province + "-" + city + "-" + county)) {
                    distirctList.add(province + "-" + city + "-" + county);
                    SamplingArea area = new SamplingArea();
                    area.setAreaNameTitle(entity.getArea());
                    area.setAreaNameBody(entity.getArea());
                    //查询区县人口和建筑物概况信息
                    HosPeoEntity hosPeo = hosPeoRepository.findHosPeo(province, city, county);
                    //查询区县概况信息
                    CountiesCondition countiesCondition = countiesConditionRepository.getQxCountiesCodition(province, city, county);
                    if (hosPeo != null) {
                        //获取调查点概况城镇结构类型占比
                        List<Map<String, Object>> townStructureList = returnAreaTownStructureList(hosPeo);
                        //获取调查点概况农村结构类型占比
                        List<Map<String, Object>> villageStructureList = returnAreaVillageStructureList(hosPeo);
                        area.setArea(String.valueOf(hosPeo.getDhpCountyArea().intValue()));
                        area.setPopulation(String.valueOf(hosPeo.getDhpTotalPop().intValue()));
                        area.setHouseRatio(String.valueOf(hosPeo.getDhpHouseTatio().intValue()) + "%");
                        area.setAreaTownStructureList(townStructureList);
                        area.setAreaVillageStructureList(villageStructureList);
                    } else {
                        msgDetail.append(",").append(province).append("-").append(city).append("-").append(county).append("的人口和建筑物概况信息未维护");
                    }
                    if (countiesCondition != null) {
                        area.setCcNation(countiesCondition.getCcNation());
                        area.setCcEconomy(countiesCondition.getCcEconomy());
                        area.setCcLandform(countiesCondition.getCcLandform());
                        area.setCcClimate(countiesCondition.getCcClimate());
                        area.setCcSeismotectonics(countiesCondition.getCcSeismotectonics());
                        area.setCcTraffic(countiesCondition.getCcTraffic());
                        area.setCcDisaster(countiesCondition.getCcDisaster());
                        area.setCcFacility(countiesCondition.getCcFacility());
                        area.setCcHistory(countiesCondition.getCcHistory());
                        area.setCcTrait(countiesCondition.getCcTrait());
                        area.setCcHazard(countiesCondition.getCcHazard());
                        area.setCcReservoir(countiesCondition.getCcReservoir());
                    }
                    area.setProvince(province);
                    area.setCity(city);
                    areaList.add(area);
                    SamplingArea2 area2 = new SamplingArea2();
                    area2.setAreaNameTitle(entity.getArea());
                    area2.setTownNameBody(entity.getTownship());
                    area2.setAreaNameBody(entity.getArea());
                    area2.setHouseFeature("房屋特点");
                    area2.setEvaluationContent("抗震能力评价");
                    area2.setProvince(province);
                    area2.setCity(city);
                    areaList2.add(area2);
                }
                Map<String, Object> map = new HashMap<>();
                map.put("province", province);
                map.put("area", city + "" + county);
                map.put("township", entity.getTownship());
                map.put("surveyName", entity.getFieldSurveyName());
                list.add(map);
            });
        }
        //2.3调查点概况
        if (PlatformObjectUtils.isNotEmpty(areaList)) {
            AtomicInteger tableInteger = new AtomicInteger(1);
            for (int i = 0; i < areaList.size(); i++) {
                areaList.get(i).setTownTableIndex("" + tableInteger.getAndAdd(1));
                areaList.get(i).setVillageTableIndex("" + tableInteger.getAndIncrement());
                List<SamplingEntity> samplingEntities = streetMap.get(areaList.get(i).getProvince() + "_" + areaList.get(i).getCity() + "_" + areaList.get(i).getAreaNameBody());
                //VillageTownHosPeoEntity villageTownHosPeo = villageTownHosPeoRepository.findHosPeo(samplingEntities.get(i).getProvince(),samplingEntities.get(i).getCity(),samplingEntities.get(i).getArea(),samplingEntities.get(i).getTownship());
                //查询乡镇概况信息
//                VillageTownCondition villageCountiesCodition = villageTownConditionRepository.getVillageCountiesCodition(samplingEntities.get(i).getProvince(),samplingEntities.get(i).getCity(),samplingEntities.get(i).getArea(),samplingEntities.get(i).getTownship());
//                if(PlatformObjectUtils.isNotEmpty(samplingEntities)){
                Map<String, String> map = new HashMap<>();
                for (SamplingEntity samplingEntity : samplingEntities) {
                    map.put(samplingEntity.getProvince() + "_" + samplingEntity.getCity() + "_" + samplingEntity.getArea() + "_" + samplingEntity.getTownship(), "1");
                }
                List<SamplingTown> townList = new ArrayList<>();
                if (map.values().size() > 0) {
                    AtomicInteger yy = new AtomicInteger(1);
                    String areaNameTitle = areaList.get(i).getAreaNameTitle();
                    char[] chars = areaNameTitle.toCharArray();
                    map.forEach((k, v) -> {
                        StringBuilder builder = new StringBuilder("");
                        StringBuilder append = builder.append(chars[0]).append(chars[1]).append(chars[2]);
                        int i2 = yy.get();
                        String index = append.append(".").append(i2).toString();
                        SamplingTown town = new SamplingTown();
                        VillageTownHosPeoEntity villageHosPeo = villageTownHosPeoRepository.findHosPeo(k.split("_")[0], k.split("_")[1], k.split("_")[2], k.split("_")[3]);
                        //查询乡镇概况信息
                        VillageTownCondition villageTownCondition = villageTownConditionRepository.getVillageCountiesCodition(k.split("_")[0], k.split("_")[1], k.split("_")[2], k.split("_")[3]);
                        town.setTownNameTitle(k.split("_")[3]).setTownNameBody(k.split("_")[3])
                                .setProvince(k.split("_")[0])
                                .setCity(k.split("_")[1])
                                .setAreaName(k.split("_")[2]);
                        if (villageHosPeo == null) {
                            //throw new RuntimeException("报告生成失败，请维护"+k.split("_")[0]+"-"+k.split("_")[1]+"-"+k.split("_")[2]+"-"+k.split("_")[3]+"人口和建筑物概况");
                            msgDetail.append(",").append(k.split("_")[0]).append("-").append(k.split("_")[1]).append("-").append(k.split("_")[2]).append("-").append(k.split("_")[3]).append("未维护人口和建筑物概况");
                        } else {
                            List<Map<String, Object>> townStructureList = returnTownStructureList(villageHosPeo);
                            List<Map<String, Object>> villageStructureList = returnVillageStructureList(villageHosPeo);
                            town.setArea(villageHosPeo.getDhpCountyArea().toString()).setPopulation(String.valueOf(villageHosPeo.getDhpTotalPop().intValue())).setHouseRatio(String.valueOf(villageHosPeo.getDhpHouseTatio().intValue()) + "%")
                                    .setTownStructureList(townStructureList)
                                    .setVillageStructureList(villageStructureList);
                        }
                        if (villageTownCondition == null) {
                            //throw new RuntimeException("报告生成失败，请维护"+k.split("_")[0]+"-"+k.split("_")[1]+"-"+k.split("_")[2]+"-"+k.split("_")[3]+"人口和建筑物概况");
                            msgDetail.append(",").append(k.split("_")[0]).append("-").append(k.split("_")[1]).append("-").append(k.split("_")[2]).append("-").append(k.split("_")[3]).append("未维护乡镇概况信息");
                        } else {
                            town.setCcNation(villageTownCondition.getCcNation());
                            town.setCcEconomy(villageTownCondition.getCcEconomy());
                            town.setCcLandform(villageTownCondition.getCcLandform());
                            town.setCcClimate(villageTownCondition.getCcClimate());
                            town.setCcSeismotectonics(villageTownCondition.getCcSeismotectonics());
                            town.setCcTraffic(villageTownCondition.getCcTraffic());
                            town.setCcDisaster(villageTownCondition.getCcDisaster());
                            town.setCcFacility(villageTownCondition.getCcFacility());
                            town.setCcTrait(villageTownCondition.getCcTrait());
                            town.setCcHazard(villageTownCondition.getCcHazard());
                            town.setCcReservoir(villageTownCondition.getCcReservoir());
                        }
                        town.setTownTableIndex("" + tableInteger.getAndIncrement());
                        town.setVillageTableIndex("" + tableInteger.getAndIncrement());
                        List<SamplingEntity> villageList = villageMap.get(town.getProvince() + "_" + town.getCity() + "_" + town.getAreaName() + "_" + town.getTownNameBody());
                        List<SamplingVillage> samplingVillageList = new ArrayList<>();
                        if (PlatformObjectUtils.isNotEmpty(villageList)) {
                            for (int i1 = 0; i1 < villageList.size(); i1++) {
                                SamplingVillage samplingVillage = new SamplingVillage();
                                String text = "";
                                if ("是".equals(villageList.get(i1).getIsDisaster())) {
                                    if (StringUtils.isNotBlank(villageList.get(i1).getDisasterScale())) {
                                        text += villageList.get(i1).getDisasterScale();
                                    }
                                    if (StringUtils.isNotBlank(villageList.get(i1).getDisasterType())) {
                                        text += villageList.get(i1).getDisasterType();
                                    }
                                }
                                text += "地质灾害点";
                                samplingVillage.setVillageNameTitle(villageList.get(i1).getFieldSurveyName()).setVillageNamebody(villageList.get(i1).getFieldSurveyName())
                                        .setTownName(villageList.get(i1).getTownship()).setHouseNum(villageList.get(i1).getTotalHouseholdNum())
                                        .setPopulation(villageList.get(i1).getTotalPopulation()).setResident(villageList.get(i1).getActualResidentPopulation())
                                        .setOuter(villageList.get(i1).getMigrantWorkers()).setChild(villageList.get(i1).getChildrenProportion())
                                        .setAuditNum(villageList.get(i1).getYoungProportion()).setOldNum(villageList.get(i1).getOldAgeProportion())
                                        .setLoadStatus(villageList.get(i1).getTrafficConditions()).setLocation(villageList.get(i1).getEnvironment())
                                        .setSchoolStatus("是".equals(villageList.get(i1).getIsSchool()) ? "有学校，学生数量约" + (StringUtils.isNotBlank(villageList.get(i1).getStudentNum()) ? villageList.get(i1).getStudentNum() : "") + "人，教室" + (StringUtils.isNotBlank(villageList.get(i1).getClassroomNum()) ? villageList.get(i1).getClassroomNum() : "") + "间" : "无学校")
                                        .setHospital("是".equals(villageList.get(i1).getIsHospital()) ? "有医院，医生" + (StringUtils.isNotBlank(villageList.get(i1).getDoctorNum()) ? villageList.get(i1).getDoctorNum() : "") + "名，床位数" + (StringUtils.isNotBlank(villageList.get(i1).getBedNum()) ? villageList.get(i1).getBedNum() : "") + "个" : "无医院")
                                        .setDisasterPoint("是".equals(villageList.get(i1).getIsDisaster()) ? "有" + text : "无" + text)
                                        .setReser("是".equals(villageList.get(i1).getIsReservoir()) ? "有水库" : "无水库");
                                samplingVillageList.add(samplingVillage);
                            }
                        }
                        town.setVillageList(samplingVillageList);
                        yy.getAndIncrement();
                        townList.add(town);
                    });
                    areaList.get(i).setTownList(townList);
                }
            }
        }
        //2.4房屋特点及抗震能力评价
        if (PlatformObjectUtils.isNotEmpty(areaList2)) {
            for (int i = 0; i < areaList2.size(); i++) {
                List<SamplingEntity> samplingEntities = streetMap.get(areaList2.get(i).getProvince() + "_" + areaList2.get(i).getCity() + "_" + areaList2.get(i).getAreaNameBody());
                if (PlatformObjectUtils.isNotEmpty(samplingEntities)) {
                    Map<String, SamplingEntity> map = new HashMap<>();
                    List<SamplingVillage2> village2List = new ArrayList<>();
                    AtomicInteger yy = new AtomicInteger(1);
                    String houseFeature = areaList2.get(i).getHouseFeature();
                    char[] chars = houseFeature.toCharArray();
                    for (SamplingEntity v : samplingEntities) {
                        //map.put(samplingEntity.getProvince()+"_"+samplingEntity.getCity()+"_"+samplingEntity.getArea()+"_"+samplingEntity.getTownship(),samplingEntity);
                        StringBuilder builder = new StringBuilder("");
                        StringBuilder append = builder.append(chars[0]).append(chars[1]).append(chars[2]).append(chars[3]);
                        String index = append.append(".").append(yy.getAndAdd(1)).toString();
                        SamplingVillage2 village2 = new SamplingVillage2();
                        village2.setTownNameTitle(v.getTownship());
                        village2.setTownNameBody(v.getTownship()).setVillageName(v.getFieldSurveyName());
                        village2.setVillageName(v.getFieldSurveyName());
                        village2.setAreaNameBody(v.getArea());
                        Map<String, Double> doubleStr = buildSortMap(v);
                        Map<String, Double> yearStr = buildSortYearMap(v);
                        StringBuilder mainStructureTypeBuilder = new StringBuilder();
                        StringBuilder conditionBuilder = new StringBuilder();
                        if (doubleStr.values().size() > 0) {
                            doubleStr.forEach((k1, v1) -> {
                                if (v1 != null && v1 > 0) {
                                    mainStructureTypeBuilder.append(k1).append("、");
                                    conditionBuilder.append(k1).append("占比约").append(v1).append("%").append(",");
                                }
                            });
                        }
                        conditionBuilder.append("房屋建造年代情况：");
                        if (yearStr.values().size() > 0) {
                            yearStr.forEach((k1, v1) -> {
                                if (v1 != null && v1 > 0) {
                                    conditionBuilder.append(k1).append("占比约").append(v1).append("%").append(",");
                                }
                            });
                        }
                        String mainStructureType = mainStructureTypeBuilder.toString();
                        mainStructureType = StringUtils.isNotBlank(mainStructureType) ? (mainStructureType.substring(0, mainStructureType.length() - 1)) : "";
                        String structureCondition = conditionBuilder.toString();
                        structureCondition = StringUtils.isNotBlank(structureCondition) ? (structureCondition.substring(0, structureCondition.length() - 1)) : "";
                        village2.setStructureStyle(mainStructureType).setStructureCondition(structureCondition);
                        List<BuildingStructure> structureList = new ArrayList<>();
                        AtomicInteger kk = new AtomicInteger(1);
                        Map<String, String> structureFutureStr = buildSortStructureFutureMap(v);
                        structureFutureStr.forEach((k11, v11) -> {
                            BuildingStructure buildingStructure = new BuildingStructure();
                            buildingStructure.setStructureName("（" + kk + "） " + k11);
                            String type = "";
                            if ("高层结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getHighFeature());
                                type = "0";
                            }
                            if ("钢结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getSteelFeature());
                                type = "1";
                            }
                            if ("多层钢筋混凝土结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getConcreteFeature());
                                type = "2";
                            }
                            if ("砖混结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getMasonryFeature());
                                type = "3";
                            }
                            if ("砖木结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getBrickWoodFeature());
                                type = "4";
                            }
                            if ("土结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getSoilFeature());
                                type = "5";
                            }
                            if ("木结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getWoodFeature());
                                type = "6";
                            }
                            if ("石层结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getStoneFeature());
                                type = "7";
                            }
                            if ("其他结构".equals(k11)) {
                                buildingStructure.setStructureFeature("  " + v.getOtherFeature());
                                type = "8";
                            }
                            List<BuildingEntityVO> buildingEntityList = buildingReqository.queryBuildingEntityData(v.getProvince(), v.getCity(), v.getArea(), v.getFieldSurveyName(), type);
                            List<AttachmentInfoEntity> structurePicList = null;
                            List<Map<String, PictureRenderData>> picList = new ArrayList<>();
                            if (buildingEntityList != null) {
                                for (BuildingEntityVO buildingEntity : buildingEntityList) {
                                    if (PlatformObjectUtils.isNotEmpty(buildingEntity.getSpecifyPicture())) {
                                        if (StringUtils.isNotBlank(buildingEntity.getSpecifyPicture())) {
                                            structurePicList = attachmentInfoRepository.findInIdList(Arrays.asList(buildingEntity.getSpecifyPicture().split(",")));
                                        }
                                        if (PlatformObjectUtils.isNotEmpty(structurePicList) && structurePicList.size() > 0) {
                                            for (AttachmentInfoEntity entity : structurePicList) {
                                                Map<String, PictureRenderData> pictureMap = new HashMap<>();
                                                pictureMap.put("picture", new PictureRenderData(255, 160, entity.getFileDirId() + entity.getAttachPath()));
                                                picList.add(pictureMap);
                                            }
                                            ;
                                        }
                                    }
                                }
                            }
                            buildingStructure.setStructurePicList(picList);
                            structureList.add(buildingStructure);
                            kk.getAndIncrement();
                        });
                        String typePieId = v.getTypePieId();
                        String yearsPieId = v.getYearsPieId();
                        List<AttachmentInfoEntity> dcdPicList = new ArrayList<>();
                        if (StringUtils.isNotBlank(typePieId) || StringUtils.isNotBlank(yearsPieId)) {
                            dcdPicList = attachmentInfoRepository.findInIdList(Arrays.asList(typePieId, yearsPieId));
                        }
                        List<Map<String, PictureRenderData>> mapList = new ArrayList<>();
                        if (PlatformObjectUtils.isNotEmpty(dcdPicList) && dcdPicList.size() > 0) {
                            for (AttachmentInfoEntity entity : dcdPicList) {
                                Map<String, PictureRenderData> pictureMap = new HashMap<>();
                                pictureMap.put("picture", new PictureRenderData(255, 160, entity.getFileDirId() + entity.getAttachPath()));
                                mapList.add(pictureMap);
                            }
                            ;
                        }
                        village2.setDcdPictures(mapList);
                        village2.setStructureList(structureList);
                        //yy.getAndIncrement();
                        village2List.add(village2);
                    }
                    areaList2.get(i).setVillage2List(village2List);
                }
            }
        }
        tatalMap.put("samplingInfoList", list);
        tatalMap.put("areaList2", areaList);
        tatalMap.put("areaList3", areaList2);
        return tatalMap;
    }

    private Map<String, Double> buildSortYearMap(SamplingEntity samplingEntity) {
        Map<String, Double> map = new LinkedHashMap<>(9);
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild70sBefore()) && Double.valueOf(samplingEntity.getBuild70sBefore()) > 0.0) {
            map.put("1970年以前", Double.valueOf(samplingEntity.getBuild70sBefore()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild70s()) && Double.valueOf(samplingEntity.getBuild70s()) > 0.0) {
            map.put("1971年-1980年", Double.valueOf(samplingEntity.getBuild70s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild80s()) && Double.valueOf(samplingEntity.getBuild80s()) > 0.0) {
            map.put("1981年-1990年", Double.valueOf(samplingEntity.getBuild80s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild90s()) && Double.valueOf(samplingEntity.getBuild90s()) > 0.0) {
            map.put("1991年-2000年", Double.valueOf(samplingEntity.getBuild90s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild00s()) && Double.valueOf(samplingEntity.getBuild00s()) > 0.0) {
            map.put("2001年-2010年", Double.valueOf(samplingEntity.getBuild00s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild10s()) && Double.valueOf(samplingEntity.getBuild10s()) > 0.0) {
            map.put("2011年-2015年", Double.valueOf(samplingEntity.getBuild10s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild16s()) && Double.valueOf(samplingEntity.getBuild16s()) > 0.0) {
            map.put("2016年-2020年", Double.valueOf(samplingEntity.getBuild16s()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBuild20s()) && Double.valueOf(samplingEntity.getBuild20s()) > 0.0) {
            map.put("2021年及以后", Double.valueOf(samplingEntity.getBuild20s()));
        }
//        List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
//        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
//
//            @Override
//            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
//                return (int) (o2.getValue() - o1.getValue());
//            }
//        });
//        Map result = new LinkedHashMap();
//        for (Map.Entry<String, Double> entry : list) {
//            result.put(entry.getKey(), entry.getValue());
//        }
        return map;
    }

    private Map<String, String> buildSortStructureFutureMap(SamplingEntity samplingEntity) {
        Map<String, String> map = new LinkedHashMap<>(9);
        if (StringUtils.isNotBlank(samplingEntity.getHighFeature())) {
            map.put("高层结构", samplingEntity.getHighFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getSteelFeature())) {
            map.put("钢结构", samplingEntity.getSteelFeature());
        }
        if (StringUtils.isNotBlank(samplingEntity.getConcreteFeature())) {
            map.put("多层钢筋混凝土结构", samplingEntity.getConcreteFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getMasonryFeature())) {
            map.put("砖混结构", samplingEntity.getMasonryFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getBrickWoodFeature())) {
            map.put("砖木结构", samplingEntity.getBrickWoodFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getSoilFeature())) {
            map.put("土结构", samplingEntity.getSoilFeature());
        }
        if (StringUtils.isNotBlank(samplingEntity.getWoodFeature())) {
            map.put("木结构", samplingEntity.getWoodFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getStoneFeature())) {
            map.put("石结构", samplingEntity.getStoneFeature());
        }

        if (StringUtils.isNotBlank(samplingEntity.getOtherFeature())) {
            map.put("其他结构", samplingEntity.getOtherFeature());
        }
        return map;
    }

    private Map<String, Double> buildSortMap(SamplingEntity samplingEntity) {
        Map<String, Double> map = new LinkedHashMap<>(9);
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getHighStructure()) && Double.valueOf(samplingEntity.getHighStructure()) > 0.0) {
            map.put("高层结构", Double.valueOf(samplingEntity.getHighStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getSteelStructure()) && Double.valueOf(samplingEntity.getSteelStructure()) > 0.0) {
            map.put("钢结构", Double.valueOf(samplingEntity.getSteelStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getConcreteStructure()) && Double.valueOf(samplingEntity.getConcreteStructure()) > 0.0) {
            map.put("多层钢筋混凝土结构", Double.valueOf(samplingEntity.getConcreteStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getMasonryStructure()) && Double.valueOf(samplingEntity.getMasonryStructure()) > 0.0) {
            map.put("砖混结构", Double.valueOf(samplingEntity.getMasonryStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getBrickWoodStructure()) && Double.valueOf(samplingEntity.getBrickWoodStructure()) > 0.0) {
            map.put("砖木结构", Double.valueOf(samplingEntity.getBrickWoodStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getSoilStructure()) && Double.valueOf(samplingEntity.getSoilStructure()) > 0.0) {
            map.put("土结构", Double.valueOf(samplingEntity.getSoilStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getWoodStructure()) && Double.valueOf(samplingEntity.getWoodStructure()) > 0.0) {
            map.put("木结构", Double.valueOf(samplingEntity.getWoodStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getStoneStructure()) && Double.valueOf(samplingEntity.getStoneStructure()) > 0.0) {
            map.put("石结构", Double.valueOf(samplingEntity.getStoneStructure()));
        }
        if (PlatformObjectUtils.isNotEmpty(samplingEntity.getOtherStructure()) && Double.valueOf(samplingEntity.getOtherStructure()) > 0.0) {
            map.put("其他结构", Double.valueOf(samplingEntity.getOtherStructure()));
        }
        List<Map.Entry<String, Double>> list = new ArrayList<Map.Entry<String, Double>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
                return (int) (o2.getValue() - o1.getValue());
            }
        });
        Map result = new LinkedHashMap();
        for (Map.Entry<String, Double> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }

    private List<Map<String, Object>> returnVillageStructureList(VillageTownHosPeoEntity hosPeo) {
        List<Map<String, Object>> villageStructureList = new ArrayList<>(9);
        Map<String, Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageHighTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSteelTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBetonTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBrickTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageMasonryTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSoilTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageWoodTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageStoneTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageOtherTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        return villageStructureList;
    }

    private List<Map<String, Object>> returnTownStructureList(VillageTownHosPeoEntity hosPeo) {
        List<Map<String, Object>> townStructureList = new ArrayList<>(9);
        Map<String, Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        if (hosPeo == null || hosPeo.getDhpTownHighTatio() == null) {
            System.out.println("1");
        }
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownHighTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSteelTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBetonTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBrickTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownMasonryTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSoilTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownWoodTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownStoneTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownOtherTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        return townStructureList;
    }

    private List<Map<String, Object>> returnAreaTownStructureList(HosPeoEntity hosPeo) {
        List<Map<String, Object>> townStructureList = new ArrayList<>(9);
        Map<String, Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownHighTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSteelTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBetonTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownBrickTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownMasonryTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownSoilTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownWoodTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownStoneTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpTownOtherTatio().intValue()) + "%");
        townStructureList.add(townStructureMap);
        return townStructureList;
    }

    private List<Map<String, Object>> returnAreaVillageStructureList(HosPeoEntity hosPeo) {
        List<Map<String, Object>> villageStructureList = new ArrayList<>(9);
        Map<String, Object> townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "高层建筑");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageHighTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "钢结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSteelTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "多层钢筋混凝土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBetonTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖混结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageBrickTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "砖木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageMasonryTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "土结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageSoilTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "木结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageWoodTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "石结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageStoneTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        townStructureMap = new HashMap<>();
        townStructureMap.put("structureTypeName", "其他结构");
        townStructureMap.put("ratio", String.valueOf(hosPeo.getDhpVillageOtherTatio().intValue()) + "%");
        villageStructureList.add(townStructureMap);
        return villageStructureList;
    }

    /**
     * 获取简本版本2中3-1~3-3 表数据
     */
    private Map<String, Object> getSuggestion(PreAssessTaskEntity task, String level, List<AreaVO> voList, StringBuilder msg) {
        //level 1:地市；2区县
        Map<String, Object> map = new HashMap<>();
        List<PreAssessTaskEntity> subTaskList = preAssessTaskRepository.getSubTask(task.getId());
        List<Suggestion> disasterSuggestList = new ArrayList<>();
        List<Preparedness> preparednessList = new ArrayList<>();
        List<Disposal> disposalList = new ArrayList<>();
        List<AnnualRisk> riskList = new ArrayList<>();
        if (PlatformObjectUtils.isNotEmpty(subTaskList) && subTaskList.size() > 0) {
            //获取子任务的分析
            subTaskList.forEach(entity -> {
                String taskNum = entity.getTaskNum();
                List<DisasterScenarioEntity> disasterScenarioEntities = suggestionAnalysisRepository.querySuggestionByTaskNum(taskNum);
                if (PlatformObjectUtils.isEmpty(disasterScenarioEntities) || disasterScenarioEntities.size() == 0) {
                    if (StringUtils.isNotBlank(msg)) {
                        msg.append("地震灾害特点和应重点关注应急事项未维护。");
                    }
                }
                if ("1".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(disasterScenarioEntities) && disasterScenarioEntities.size() > 0) {
                        List<DisasterScenarioEntity> collect = disasterScenarioEntities.stream().filter(disasterScenarioEntity -> "1".equals(disasterScenarioEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Suggestion suggestion = new Suggestion();
                            suggestion.setAreaName(des.getCity())
                                    .setBuildingDamage(des.getBuildingDamage())
                                    .setCasualties(des.getCasualties())
                                    .setGeologicHazard(des.getGeologicHazard())
                                    .setSecondaryDisaster(des.getSecondaryDisaster())
                                    .setEarthquakeTraffic(des.getEarthquakeTraffic())
                                    .setOtherDisaster(des.getOtherDisaster());
                            disasterSuggestList.add(suggestion);
                        });
                    }
                } else if ("2".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(disasterScenarioEntities) && disasterScenarioEntities.size() > 0) {
                        List<DisasterScenarioEntity> collect = disasterScenarioEntities.stream().filter(disasterScenarioEntity -> "0".equals(disasterScenarioEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Suggestion suggestion = new Suggestion();
                            suggestion.setAreaName(des.getArea())
                                    .setBuildingDamage(des.getBuildingDamage())
                                    .setCasualties(des.getCasualties())
                                    .setGeologicHazard(des.getGeologicHazard())
                                    .setSecondaryDisaster(des.getSecondaryDisaster())
                                    .setEarthquakeTraffic(des.getEarthquakeTraffic())
                                    .setOtherDisaster(des.getOtherDisaster());
                            disasterSuggestList.add(suggestion);
                        });
                    }
                }
                List<EmergencyDisasterEntity> emergencyDisasterEntities = suggestionAnalysisRepository.queryEmergencyByTaskNum(taskNum);
                if (PlatformObjectUtils.isEmpty(disasterScenarioEntities) || disasterScenarioEntities.size() == 0) {
                    msg.append("地震应急准备建议未维护。");
                }
                if ("1".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(emergencyDisasterEntities) && emergencyDisasterEntities.size() > 0) {
                        List<EmergencyDisasterEntity> collect = emergencyDisasterEntities.stream().filter(emergencyDisasterEntity -> "1".equals(emergencyDisasterEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Preparedness preparedness = new Preparedness();
                            preparedness.setAreaName(des.getCity())
                                    .setSystem(des.getEmergencySystem()).setWorking(des.getEmergencyWorkingMechanism())
                                    .setSupplies(des.getEmergencySuppliesReserve()).setRescue(des.getEmergencyRescueForce())
                                    .setShelter(des.getEmergencyShelter()).setSupportability(des.getSupportability())
                                    .setCapacity(des.getRumorEmergencyCapacity()).setPopularization(des.getPopularization())
                                    .setOther(des.getOtherMeasures());
                            preparednessList.add(preparedness);
                        });
                    }
                } else if ("2".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(emergencyDisasterEntities) && emergencyDisasterEntities.size() > 0) {
                        List<EmergencyDisasterEntity> collect = emergencyDisasterEntities.stream().filter(emergencyDisasterEntity -> "0".equals(emergencyDisasterEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Preparedness preparedness = new Preparedness();
                            preparedness.setAreaName(des.getArea())
                                    .setSystem(des.getEmergencySystem()).setWorking(des.getEmergencyWorkingMechanism())
                                    .setSupplies(des.getEmergencySuppliesReserve()).setRescue(des.getEmergencyRescueForce())
                                    .setShelter(des.getEmergencyShelter()).setSupportability(des.getSupportability())
                                    .setCapacity(des.getRumorEmergencyCapacity()).setPopularization(des.getPopularization())
                                    .setOther(des.getOtherMeasures());
                            preparednessList.add(preparedness);
                        });
                    }
                }
                List<EmergencyDisposalEntity> emergencyDisposalEntities = suggestionAnalysisRepository.queryEmergencyDisposalByTaskNum(taskNum);
                if (PlatformObjectUtils.isEmpty(emergencyDisposalEntities) || emergencyDisposalEntities.size() == 0) {
                    msg.append("地震应急处置建议未维护。");
                }
                if ("1".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(emergencyDisposalEntities) && emergencyDisposalEntities.size() > 0) {
                        List<EmergencyDisposalEntity> collect = emergencyDisposalEntities.stream().filter(emergencyDisposalEntity -> "1".equals(emergencyDisposalEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Disposal disposal = new Disposal();
                            disposal.setAreaName(des.getCity())
                                    .setInput(des.getRescueForceMaterialInput()).setCritical(des.getEarthquakeDisasterCriticalArea())
                                    .setTraffic(des.getTrafficSystemSupportRepair()).setCommunications(des.getCommunicationsSystemSupportRepair())
                                    .setPower(des.getPowerSystemSupportRepair()).setImportant(des.getImportantFacilitiesCheck())
                                    .setClimate(des.getClimateFeatureReply()).setNation(des.getNationFeatureReply())
                                    .setRumor(des.getRumorReply()).setOther(des.getOtherFeatureReply());
                            disposalList.add(disposal);
                        });
                    }
                } else if ("2".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(emergencyDisposalEntities) && emergencyDisposalEntities.size() > 0) {
                        List<EmergencyDisposalEntity> collect = emergencyDisposalEntities.stream().filter(emergencyDisposalEntity -> "0".equals(emergencyDisposalEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            Disposal disposal = new Disposal();
                            disposal.setAreaName(des.getArea())
                                    .setInput(des.getRescueForceMaterialInput()).setCritical(des.getEarthquakeDisasterCriticalArea())
                                    .setTraffic(des.getTrafficSystemSupportRepair()).setCommunications(des.getCommunicationsSystemSupportRepair())
                                    .setPower(des.getPowerSystemSupportRepair()).setImportant(des.getImportantFacilitiesCheck())
                                    .setClimate(des.getClimateFeatureReply()).setNation(des.getNationFeatureReply())
                                    .setRumor(des.getRumorReply()).setOther(des.getOtherFeatureReply());
                            disposalList.add(disposal);
                        });
                    }
                }
                List<AnnualRiskEntity> annualRiskDataByTaskNum = annualRiskService.getAnnualRiskDataByTaskNum(taskNum);
                if ("1".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(annualRiskDataByTaskNum) && annualRiskDataByTaskNum.size() > 0) {
                        List<AnnualRiskEntity> collect = annualRiskDataByTaskNum.stream().filter(annualRiskEntity -> "1".equals(annualRiskEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            AnnualRisk annualRisk = new AnnualRisk();
                            annualRisk.setAreaName(des.getCity())
                                    .setBuilding(des.getBuilding()).setDisasterHiddenDanger(des.getDisasterHiddenDanger())
                                    .setLifelineSystem(des.getLifelineSystem()).setMajorInfrastructure(des.getMajorInfrastructure()).setOtherAnnualDisaster(des.getOtherAnnualDisaster());
                            riskList.add(annualRisk);
                        });
                    }
                } else if ("2".equals(level)) {
                    if (PlatformObjectUtils.isNotEmpty(annualRiskDataByTaskNum) && annualRiskDataByTaskNum.size() > 0) {
                        List<AnnualRiskEntity> collect = annualRiskDataByTaskNum.stream().filter(annualRiskEntity -> "0".equals(annualRiskEntity.getDivisionFlag())).collect(Collectors.toList());
                        collect.forEach(des -> {
                            AnnualRisk annualRisk = new AnnualRisk();
                            annualRisk.setAreaName(des.getArea())
                                    .setBuilding(des.getBuilding()).setDisasterHiddenDanger(des.getDisasterHiddenDanger())
                                    .setLifelineSystem(des.getLifelineSystem()).setMajorInfrastructure(des.getMajorInfrastructure()).setOtherAnnualDisaster(des.getOtherAnnualDisaster());
                            riskList.add(annualRisk);
                        });
                    }
                }
            });
        } else {
            //获取父任务的分析
            List<DisasterScenarioEntity> disasterScenarioEntities = suggestionAnalysisRepository.querySuggestionByTaskNum(task.getTaskNum());
            if (PlatformObjectUtils.isEmpty(disasterScenarioEntities) || disasterScenarioEntities.size() == 0) {
                msg.append("地震灾害特点和应重点关注应急事项未维护。");
            }
            if ("1".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(disasterScenarioEntities) && disasterScenarioEntities.size() > 0) {
                    List<DisasterScenarioEntity> collect = disasterScenarioEntities.stream().filter(disasterScenarioEntity -> "1".equals(disasterScenarioEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Suggestion suggestion = new Suggestion();
                        suggestion.setAreaName(des.getCity())
                                .setBuildingDamage(des.getBuildingDamage())
                                .setCasualties(des.getCasualties())
                                .setGeologicHazard(des.getGeologicHazard())
                                .setSecondaryDisaster(des.getSecondaryDisaster())
                                .setEarthquakeTraffic(des.getEarthquakeTraffic())
                                .setOtherDisaster(des.getOtherDisaster());
                        disasterSuggestList.add(suggestion);
                    });
                }
            } else if ("2".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(disasterScenarioEntities) && disasterScenarioEntities.size() > 0) {
                    List<DisasterScenarioEntity> collect = disasterScenarioEntities.stream().filter(disasterScenarioEntity -> "0".equals(disasterScenarioEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Suggestion suggestion = new Suggestion();
                        suggestion.setAreaName(des.getArea())
                                .setBuildingDamage(des.getBuildingDamage())
                                .setCasualties(des.getCasualties())
                                .setGeologicHazard(des.getGeologicHazard())
                                .setSecondaryDisaster(des.getSecondaryDisaster())
                                .setEarthquakeTraffic(des.getEarthquakeTraffic())
                                .setOtherDisaster(des.getOtherDisaster());
                        disasterSuggestList.add(suggestion);
                    });
                }
            }
            List<EmergencyDisasterEntity> emergencyDisasterEntities = suggestionAnalysisRepository.queryEmergencyByTaskNum(task.getTaskNum());
            if (PlatformObjectUtils.isEmpty(disasterScenarioEntities) || disasterScenarioEntities.size() == 0) {
                msg.append("地震应急准备建议未维护。");
            }
            if ("1".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(emergencyDisasterEntities) && emergencyDisasterEntities.size() > 0) {
                    List<EmergencyDisasterEntity> collect = emergencyDisasterEntities.stream().filter(emergencyDisasterEntity -> "1".equals(emergencyDisasterEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Preparedness preparedness = new Preparedness();
                        preparedness.setAreaName(des.getCity())
                                .setSystem(des.getEmergencySystem()).setWorking(des.getEmergencyWorkingMechanism())
                                .setSupplies(des.getEmergencySuppliesReserve()).setRescue(des.getEmergencyRescueForce())
                                .setShelter(des.getEmergencyShelter()).setSupportability(des.getSupportability())
                                .setCapacity(des.getRumorEmergencyCapacity()).setPopularization(des.getPopularization())
                                .setOther(des.getOtherMeasures());
                        preparednessList.add(preparedness);
                    });
                }
            } else if ("2".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(emergencyDisasterEntities) && emergencyDisasterEntities.size() > 0) {
                    List<EmergencyDisasterEntity> collect = emergencyDisasterEntities.stream().filter(emergencyDisasterEntity -> "0".equals(emergencyDisasterEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Preparedness preparedness = new Preparedness();
                        preparedness.setAreaName(des.getArea())
                                .setSystem(des.getEmergencySystem()).setWorking(des.getEmergencyWorkingMechanism())
                                .setSupplies(des.getEmergencySuppliesReserve()).setRescue(des.getEmergencyRescueForce())
                                .setShelter(des.getEmergencyShelter()).setSupportability(des.getSupportability())
                                .setCapacity(des.getRumorEmergencyCapacity()).setPopularization(des.getPopularization())
                                .setOther(des.getOtherMeasures());
                        preparednessList.add(preparedness);
                    });
                }
            }

            List<EmergencyDisposalEntity> emergencyDisposalEntities = suggestionAnalysisRepository.queryEmergencyDisposalByTaskNum(task.getTaskNum());
            if (PlatformObjectUtils.isEmpty(emergencyDisposalEntities) || emergencyDisposalEntities.size() == 0) {
                msg.append("地震应急处置建议未维护。");
            }
            if ("1".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(emergencyDisposalEntities) && emergencyDisposalEntities.size() > 0) {
                    List<EmergencyDisposalEntity> collect = emergencyDisposalEntities.stream().filter(emergencyDisposalEntity -> "1".equals(emergencyDisposalEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Disposal disposal = new Disposal();
                        disposal.setAreaName(des.getCity())
                                .setInput(des.getRescueForceMaterialInput()).setCritical(des.getEarthquakeDisasterCriticalArea())
                                .setTraffic(des.getTrafficSystemSupportRepair()).setCommunications(des.getCommunicationsSystemSupportRepair())
                                .setPower(des.getPowerSystemSupportRepair()).setImportant(des.getImportantFacilitiesCheck())
                                .setClimate(des.getClimateFeatureReply()).setNation(des.getNationFeatureReply())
                                .setRumor(des.getRumorReply()).setOther(des.getOtherFeatureReply());
                        disposalList.add(disposal);
                    });
                }
            } else if ("2".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(emergencyDisposalEntities) && emergencyDisposalEntities.size() > 0) {
                    List<EmergencyDisposalEntity> collect = emergencyDisposalEntities.stream().filter(emergencyDisposalEntity -> "0".equals(emergencyDisposalEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        Disposal disposal = new Disposal();
                        disposal.setAreaName(des.getArea())
                                .setInput(des.getRescueForceMaterialInput()).setCritical(des.getEarthquakeDisasterCriticalArea())
                                .setTraffic(des.getTrafficSystemSupportRepair()).setCommunications(des.getCommunicationsSystemSupportRepair())
                                .setPower(des.getPowerSystemSupportRepair()).setImportant(des.getImportantFacilitiesCheck())
                                .setClimate(des.getClimateFeatureReply()).setNation(des.getNationFeatureReply())
                                .setRumor(des.getRumorReply()).setOther(des.getOtherFeatureReply());
                        disposalList.add(disposal);
                    });
                }
            }

            List<AnnualRiskEntity> annualRiskDataByTaskNum = annualRiskService.getAnnualRiskDataByTaskNum(task.getTaskNum());
            if ("1".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(annualRiskDataByTaskNum) && annualRiskDataByTaskNum.size() > 0) {
                    List<AnnualRiskEntity> collect = annualRiskDataByTaskNum.stream().filter(annualRiskEntity -> "1".equals(annualRiskEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        AnnualRisk annualRisk = new AnnualRisk();
                        annualRisk.setAreaName(des.getCity())
                                .setBuilding(des.getBuilding()).setDisasterHiddenDanger(des.getDisasterHiddenDanger())
                                .setLifelineSystem(des.getLifelineSystem()).setMajorInfrastructure(des.getMajorInfrastructure()).setOtherAnnualDisaster(des.getOtherAnnualDisaster());
                        riskList.add(annualRisk);
                    });
                }
            } else if ("2".equals(level)) {
                if (PlatformObjectUtils.isNotEmpty(annualRiskDataByTaskNum) && annualRiskDataByTaskNum.size() > 0) {
                    List<AnnualRiskEntity> collect = annualRiskDataByTaskNum.stream().filter(annualRiskEntity -> "0".equals(annualRiskEntity.getDivisionFlag())).collect(Collectors.toList());
                    collect.forEach(des -> {
                        AnnualRisk annualRisk = new AnnualRisk();
                        annualRisk.setAreaName(des.getArea())
                                .setBuilding(des.getBuilding()).setDisasterHiddenDanger(des.getDisasterHiddenDanger())
                                .setLifelineSystem(des.getLifelineSystem()).setMajorInfrastructure(des.getMajorInfrastructure()).setOtherAnnualDisaster(des.getOtherAnnualDisaster());
                        riskList.add(annualRisk);
                    });
                }
            }
        }
        map.put("disasterSuggestList", disasterSuggestList);
        map.put("preparednessList", preparednessList);
        map.put("disposalList", disposalList);
        map.put("riskList", riskList);
        return map;
    }
//    public RestResponse createDetailedReport1(String taskId, String level, String useType, String modelName, String attachId, String taskName, HttpServletResponse response) {
//        List<YpgReport> reportList = new ArrayList<>();
//        PreAssessTaskEntity task = preAssessTaskRepository.findById(taskId);
//        String taskDistrict = task.getTaskDistrict();
//        JSONObject subArea = getSubArea(taskId);
//        String areaNum =(String) subArea.get("num");
//        Map<String,Map<String,List<String>>> mapMap =(Map<String,Map<String,List<String>>>) subArea.get("mapMap");
//        List<AreaVO> voList = new ArrayList<>();
//        if(mapMap.values().size()>0){
//            mapMap.forEach((k,v)->{
//                v.forEach((k1,v1)->{
//                    v1.forEach(v11->{
//                        AreaVO vo = new AreaVO();
//                        vo.setProvince(k);
//                        vo.setCity(k1);
//                        vo.setCounty(v11);
//                        voList.add(vo);
//                    });
//                });
//            });
//        }
//        List<String> provinceList = new ArrayList<>();
//        List<String> cityList = new ArrayList<>();
//        List<String> districtList = new ArrayList<>();
//        String provinceCity = "";
//        if(StringUtils.isNotBlank(taskDistrict)){
//            String[] districtArray = taskDistrict.split("、");
//            provinceList.add(districtArray[0].split("-")[0]);
//            cityList.add(districtArray[0].split("-")[1]);
//            //List subArea = sysAreaService.getSubArea(districtArray[0], "");
//            provinceCity = districtArray[0];
//        }
//        String provinceStr = provinceCity.split("-")[0];
//        String cityStr = provinceCity.split("-")[1];
//
//
//        //根据省市县获取区县概况信息的地形地貌特征字段文字内容
//        CountiesCondition qxCountiesCodition = countiesConditionRepository.getQxCountiesCodition(provinceStr, provinceStr, cityStr);
//        if(qxCountiesCodition==null){
//            qxCountiesCodition = new CountiesCondition();
//        }
//        String landform = qxCountiesCodition.getCcLandform();
//        String weather = qxCountiesCodition.getCcClimate();
//        AtomicInteger num = new AtomicInteger(1);
//        YpgArea ypgArea = YpgArea.builder().areaNameTitle("1.2."+num.getAndIncrement()+cityStr).landform(landform).build();
//        YpgArea1 ypgArea1 = YpgArea1.builder().areaNameTitle("1.3."+num.getAndIncrement()+cityStr).weather(weather).build();
//        PopulationDetails populationDetails = new PopulationDetails();
//        populationDetails.setAreaNameBody(cityStr).setFutureDetails(qxCountiesCodition.getCcNation());
//        List<YpgArea> ypgAreaList = new ArrayList<>();
//        List<YpgArea1> ypgAreaList1 = new ArrayList<>();
//        List<PopulationDetails> populationDetailsList = new ArrayList<>();
//        populationDetailsList.add(populationDetails);
//        ypgAreaList.add(ypgArea);
//        ypgAreaList1.add(ypgArea1);
//        // 1.4人口特征（含民族特点）
//        List<Map<String,Object>> samplingEntityMapList = new ArrayList<Map<String,Object>>();
//        StringBuilder cityMsg = new StringBuilder("");
//        cityMsg.append(provinceList.size()).append("个省").append(cityList.size()).append("个市").append(districtList.size()).append("个县");
//        StringBuilder cityMsgDetails = new StringBuilder();
//        for (String province : provinceList) {
//            cityMsgDetails.append(province).append("省涉及市分别为");
//            for (String city : cityList) {
//                cityMsgDetails.append(city).append("、");
//            }
//        }
//
//        HosPeoEntity hosPeo = hosPeoRepository.findHosPeo(provinceStr, provinceStr, cityStr);
//        if(PlatformObjectUtils.isEmpty(hosPeo)){
//            return RestResponse.fail(provinceStr+"、"+provinceStr+"、"+cityStr+"的【人口和建筑物概况】未维护，请到【统计数据管理】模块中维护。");
//        }
//        List<Map<String,Object>> popList = new ArrayList<Map<String,Object>>();
//        Map<String,Object> map = new HashMap<String, Object>();
//        //省
//        map.put("province", provinceStr);
//        //市
//        map.put("city",provinceStr);
//        //区县
//        map.put("county",cityStr);
//        map.put("totalPopulation",hosPeo.getDhpTotalPop());
//        popList.add(map);
//
//        GdpEntity gdpEntity = gdpRepositpory.getGdpByDivision(provinceStr, provinceStr, cityStr);
//        List<Map<String,Object>> economyList = new ArrayList<Map<String,Object>>();
//        Map<String,Object> economyMap = new HashMap<String, Object>();
//        //省
//        economyMap.put("province", provinceStr);
//        //市
//        economyMap.put("city",provinceStr);
//        //区县
//        economyMap.put("county",cityStr);
//        economyMap.put("totalGdp",gdpEntity.getGdp());
//        economyMap.put("avgGdp",gdpEntity.getPeoAvgGdp());
//        economyList.add(economyMap);
//
//        List<BuildingResultVo> buildingResultVos = buildingReqository.queryBuildingData(task.getTaskNum(),provinceStr, provinceStr, cityStr);
//        Integer structureNum = buildingResultVos.size();
//        List<BuildingStructure> structureList = new ArrayList<>();
//        StringBuilder structureDetails = new StringBuilder();
//        YpgArea2 area2 = new YpgArea2();
//        if(PlatformObjectUtils.isNotEmpty(buildingResultVos)){
//            for (BuildingResultVo vo : buildingResultVos) {
//                BuildingStructure buildingStructure = new BuildingStructure();
//                String structureFuture = fieldSurveyTaskRepository.getStructureFuture(provinceStr, provinceStr, cityStr,vo.getBuildingStructure(),task.getTaskNum());
//                structureDetails.append(getStructureName(Integer.valueOf(vo.getBuildingStructure()))).append("、");
//                buildingStructure.setStructureName(getStructureName(Integer.valueOf(vo.getBuildingStructure())));
//                buildingStructure.setStructureFeature(structureFuture);
//                structureList.add(buildingStructure);
//            }
//        }
//        List<YpgArea2> areaList2 = new ArrayList<>();
//        String details = structureDetails.substring(0, structureDetails.length() - 1);
//        area2.setStructureList(structureList);
//        area2.setAreaNameTitle(cityStr).setAreaNameBody(cityStr).setStructureDetails(details).setStructureNum(structureNum+"");
//        areaList2.add(area2);
//        String msgDetails = cityMsgDetails.substring(0, cityMsgDetails.length() - 1);
//        Map<String, Object> paramMap = new HashMap<>();
//        Map<String, Object> reportData = null;
//        try {
//            reportData = reportDataService.getReportData(taskId);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//        List<Map<String, Object>> earthtable = new ArrayList<>();
//        if(PlatformObjectUtils.isEmpty(reportData)){
//            earthtable = (List<Map<String, Object>>) reportData.get("earthtable");
//        }
//        YpgReport report = YpgReport.builder().areaList(new ArrayList<>())
//                .areaList1(new ArrayList<>())
//                .populationList(new ArrayList<>())
//                .populationDetails(new ArrayList<>())
//                .economyList(new ArrayList<>())
//                .buildingFuture(new ArrayList<>())
//                .earthtable(new ArrayList<>())
//                .build();
//        List<YpgArea> reportAreaList = report.getAreaList();
//        List<YpgArea1> reportAreaList1 = report.getAreaList1();
//        List<Map<String, Object>> populationList = report.getPopulationList();
//        List<PopulationDetails> detailsList = report.getPopulationDetails();
//        List<Map<String, Object>> ecList = report.getEconomyList();
//        List<YpgArea2> list2 = report.getBuildingFuture();
//        List<Map<String, Object>> earthtable1 = report.getEarthtable();
//        earthtable1.addAll(earthtable);
//        list2.addAll(areaList2);
//        ecList.addAll(economyList);
//        detailsList.addAll(populationDetailsList);
//        populationList.addAll(popList);
//        reportAreaList.addAll(ypgAreaList);
//        reportAreaList1.addAll(ypgAreaList1);
//        reportList.add(report);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
//        Date date = new Date();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(date);
//        int year = calendar.get(Calendar.YEAR);
//        paramMap.put("year",year+"");
//        paramMap.put("taskName",taskName);
//        paramMap.put("createTime",sdf.format(date));
//        paramMap.put("area",task.getTaskArea());
//        paramMap.put("cityMsg",cityMsg.toString());
//        paramMap.put("cityMsgDetails","msgDetails");
//        paramMap.put("section1",reportList);
//        // 生成文件
////        AttachmentInfoEntity attach = attachmentInfoService.getAttach(attachId);
////        String fileDirId = attach.getFileDirId();
////        String attachPath = attach.getAttachPath();
//        Map<String, String> resultMap = createReport(paramMap,modelName,"attachPath","fileDirId");
//        //--生成报告逻辑结束
//        FieldReportManagement rp = new FieldReportManagement();
//        //FieldReportManagement fieldReportManagement = samplingSurveyReportRepository.getReportByTaskCode(taskCode);
//        return RestResponse.succeed(rp);
//    }

    private String getStructureName(Integer structureNum) {
        String structureName = "";
        switch (structureNum) {
            case 0:
                structureName = "高层结构";
                return structureName;
            case 1:
                structureName = "钢结构";
                return structureName;
            case 2:
                structureName = "多层钢筋混凝土结构";
                return structureName;
            case 3:
                structureName = "砖混结构";
                return structureName;
            case 4:
                structureName = "砖木结构";
                return structureName;
            case 5:
                structureName = "土结构";
                return structureName;
            case 6:
                structureName = "木结构";
                return structureName;
            case 7:
                structureName = "石结构";
                return structureName;
            case 8:
                structureName = "其他结构";
                return structureName;
            default:
                structureName = "高层结构";
                return structureName;
        }
    }

    private Map<String, String> createReport(Map<String, Object> paramMap, String modelName, String attachPath, String fileDirId) {
        // 文件存放根目录
        //String rootPath = "D:" + File.separator+"report"+ File.separator;
        String rootPath = localDir;
        File dir = new File(rootPath);
        // 文件夹不存在则创建ss
        if (!dir.exists()) {
            boolean mkdir = dir.mkdir();
        }
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowStr = sdf.format(now);
        String desFileName = "地震灾害损失预评估和应急处置要点报告（详本）报告" + nowStr + ".docx";
        String docxPath = rootPath + File.separator + desFileName;
        // 根据模板渲染word、并且生成pdf文件 fileDirId + attachPath fileDirId + attachPath
        //ClassPathResource classPathResource = new ClassPathResource("static/地震灾害损失预评估和应急处置要点报告.docx");
        try (
                InputStream inputStream = new FileInputStream(fileDirId + attachPath)) {
            //InputStream inputStream = new FileInputStream("D:\\公司文档数据\\预评估\\地震灾害损失预评估和应急处置要点报告-详本-20231013.docx" ))  {
            //渲染表格  动态行
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            Configure config = Configure.newBuilder()
                    .bind("resultTable1", new DefineMethodPolicy())
                    .bind("injureds", policy)
                    .bind("resettleds", policy)
                    .bind("rescues", policy)
                    .bind("populationList", policy)
                    .bind("economyList", policy)
                    .bind("evaluationList", policy)
                    .bind("reservoirList", policy)
                    .bind("schoolList", policy)
                    .bind("disasterList", policy)
                    .bind("resettle4", policy)
                    .bind("roadList", policy)
                    .bind("trafficAnalyseList", policy)
                    .bind("trafficAnalyseList7", policy)
                    .bind("trafficAnalyseList8", policy)
                    .bind("trafficAnalyseList9", policy)
                    .bind("trafficAnalyseList10", policy)
                    .bind("trafficAnalyseList11", policy)
                    .bind("riskEnterpriseList", policy)
                    .bind("reservesList", policy)
                    .bind("rescueList", policy)
                    .bind("equipList", policy)
                    .bind("sanctuaryList", policy)
                    .bind("medicalList", policy)
                    .bind("gasList", policy)
                    .bind("samplingInfoList", policy)
                    .bind("areaTownStructureList", policy)
                    .bind("areaVillageStructureList", policy)
                    .bind("townStructureList", policy)
                    .bind("villageStructureList", policy)
                    .bind("earthtable", policy)
                    .bind("destorytable", policy)
                    .build();
            // 通过协查函模板，开始生成电子协查函
            try (
                    XWPFTemplate template = XWPFTemplate.compile(inputStream, config).render(paramMap);
                    OutputStream outDocx = Files.newOutputStream(Paths.get(docxPath))) {
                NiceXWPFDocument xwpfDocument = template.getXWPFDocument();

                ZipSecureFile.setMinInflateRatio(-1D);
                // 输出word
                template.getXWPFDocument().write(outDocx);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<>(4);
        map.put("rootPath", rootPath);
        map.put("docxName", desFileName);
        return map;
    }

    @Override
    public String getSlopeModelIntensity(String taskId) {
        String intensity = countLandslideService.getSlopeModelIntensity(taskId);
        return intensity;
    }

    @Override
    public List<RiskEnterpriseData> getriskData(String taskId) {
        List<RiskEnterpriseData> risklist = riskEnterpriseDataService.getriskData(taskId);
        return risklist;
    }

    @Override
    public List<GasstationData> getGassData(String taskId) {
        List<GasstationData> gasslist = gasstationDataService.getGassData(taskId);
        return gasslist;
    }

    @Override
    public List<SeiEmeCapAssVO> getSeiEmeCapAss(String taskId) {
        List<SeiEmeCapAssVO> countyByTaskDistrict = getCountyByTaskDistrict(taskId);
        for (SeiEmeCapAssVO item : countyByTaskDistrict) {
            ScSeismicsetout scSeismicsetout = seismicSetoutService.findByAreaId(item.getAreaId());
            if (PlatformObjectUtils.isNotEmpty(scSeismicsetout)) {
                BeanUtils.copyProperties(scSeismicsetout, item);
                List<ScSupplies> wz = seismicSetoutRepository.getWz(scSeismicsetout.getScId());
                if (wz.size() > 0) {
                    item.setScSupplies(wz);
                }
                List<ScRescue> scRescue = seismicSetoutRepository.getScRescue(scSeismicsetout.getScId());
                if (scRescue.size() > 0) {
                    item.setScRescue(scRescue);
                }
                List<ScEquip> equip = seismicSetoutRepository.getEquip(scSeismicsetout.getScId());
                if (equip.size() > 0) {
                    item.setScEquip(equip);
                }
                List<ScSanctuary> sc = seismicSetoutRepository.getSc(scSeismicsetout.getScId());
                if (sc.size() > 0) {
                    item.setScSanctuary(sc);
                }
                List<ScMedical> me = seismicSetoutRepository.getMe(scSeismicsetout.getScId());
                if (me.size() > 0) {
                    item.setScMedical(me);
                }
            }
        }
        return countyByTaskDistrict;
    }

    @Override
    public List<ReportInfoVO> getReportInfo() {
        List<ReportInfoVO> list = reportManagementRepository.getReportInfo();
        return list;
    }

    @Override
    public Map<String, Object> getJbReportListByTaskId(String taskId, int curPage, int pageSize) {
        return reportManagementRepository.getHistoryReportByTaskId(taskId, curPage, pageSize, "1");
    }

    @Override
    public Map<String, Object> getXbReportListByTaskId(String taskId, int curPage, int pageSize) {
        return reportManagementRepository.getHistoryReportByTaskId(taskId, curPage, pageSize, "2");
    }

    @Override
    public ReportManagement getById(String id) {
        return reportManagementRepository.getReportById(id);
    }

    @Override
    public HistoryUploadReport getHistoryById(String id) {
        return reportManagementRepository.getHistoryUploadReportById(id);
    }


    private List<SeiEmeCapAssVO> getCountyByTaskDistrict(String taskId) {
        PreAssessTaskEntity task = preAssessTaskRepository.findById(taskId);
        List<SeiEmeCapAssVO> list = new ArrayList<>();
        String taskDistrict = task.getTaskDistrict();
        try {
            if (!PlatformObjectUtils.isEmpty(taskDistrict)) {
                for (String district : taskDistrict.split("、")) {
                    int n = district.length() - district.replaceAll("-", "").length();
                    List<SysMenuVo> sysMenuList = null;//获取所有省
                    sysMenuList = getSAreaTree("1");
                    if (district.contains("北京市") || district.contains("天津市") || district.contains("上海市") || district.contains("重庆市")) {
                        if (n == 0) {
                            for (SysMenuVo sysMenuVo : sysMenuList) {
                                String name = sysMenuVo.getName();
                                if (district.equals(name)) {//省名称
                                    List<SysMenuVo> citySysMenu = getSAreaTree(sysMenuVo.getValue());//获取该省下所有市
                                    for (SysMenuVo citySysMenuVo : citySysMenu) {
                                        List<SysMenuVo> areaSysMenu = getSAreaTree(citySysMenuVo.getValue());//获取市下所有区县
                                        for (SysMenuVo areaSysMenuVo : areaSysMenu) {
                                            SeiEmeCapAssVO seiEmeCapAssVO = new SeiEmeCapAssVO();
                                            seiEmeCapAssVO.setArea(areaSysMenuVo.getName());
                                            seiEmeCapAssVO.setAreaId(areaSysMenuVo.getValue());
                                            list.add(seiEmeCapAssVO);
                                        }
                                    }
                                }
                            }
                        } else if (n == 1) {
                            String province = district.split("-")[0];
                            String city = district.split("-")[0];
                            String area = district.split("-")[1];
                            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(area, "UTF-8"));
                            SeiEmeCapAssVO seiEmeCapAssVO = new SeiEmeCapAssVO();
                            seiEmeCapAssVO.setArea(area);
                            seiEmeCapAssVO.setAreaId(divisionIds.split("_")[2]);
                            list.add(seiEmeCapAssVO);
                        }
                    } else {
                        if (n == 0) {//说明只有省级,直辖市除外
                            for (SysMenuVo sysMenuVo : sysMenuList) {//遍历所有省
                                String name = sysMenuVo.getName();
                                if (district.equals(name)) {//省名称
                                    String value = sysMenuVo.getValue();//省id
                                    List<SysMenuVo> citySysMenu = getSAreaTree(value);//获取该省下所有市
                                    for (SysMenuVo citySysMenuVo : citySysMenu) {
                                        String cityValue = citySysMenuVo.getValue();//市id
                                        List<SysMenuVo> areaSysMenu = getSAreaTree(cityValue);//获取市下所有区县
                                        for (SysMenuVo areaSysMenuVo : areaSysMenu) {
                                            SeiEmeCapAssVO seiEmeCapAssVO = new SeiEmeCapAssVO();
                                            seiEmeCapAssVO.setArea(areaSysMenuVo.getName());
                                            seiEmeCapAssVO.setAreaId(areaSysMenuVo.getValue());
                                            list.add(seiEmeCapAssVO);
                                        }
                                    }
                                }
                            }
                        } else if (n == 1) {//有省市两级
                            String province = district.split("-")[0];//省
                            String city = district.split("-")[1];//市
                            for (SysMenuVo sysMenuVo : sysMenuList) {//遍历所有省
                                String provinceName = sysMenuVo.getName();
                                if (province.equals(sysMenuVo.getName())) {//省名称
                                    List<SysMenuVo> citySysMenu = getSAreaTree(sysMenuVo.getValue());//获取该省下所有市
                                    for (SysMenuVo citySysMenuVo : citySysMenu) {
                                        if (city.equals(citySysMenuVo.getName())) {
                                            List<SysMenuVo> areaSysMenu = getSAreaTree(citySysMenuVo.getValue());//获取该省下所有区县
                                            for (SysMenuVo areaSysMenuVo : areaSysMenu) {
                                                SeiEmeCapAssVO seiEmeCapAssVO = new SeiEmeCapAssVO();
                                                seiEmeCapAssVO.setArea(areaSysMenuVo.getName());
                                                seiEmeCapAssVO.setAreaId(areaSysMenuVo.getValue());
                                                list.add(seiEmeCapAssVO);
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (n == 2) {
                            String province = district.split("-")[0];
                            String city = district.split("-")[0];
                            String area = district.split("-")[1];
                            String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(province, "UTF-8"), URLEncoder.encode(city, "UTF-8"), URLEncoder.encode(area, "UTF-8"));
                            SeiEmeCapAssVO seiEmeCapAssVO = new SeiEmeCapAssVO();
                            seiEmeCapAssVO.setArea(area);
                            seiEmeCapAssVO.setAreaId(divisionIds.split("_")[2]);
                            list.add(seiEmeCapAssVO);
                        }
                    }
                }

            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return list;
    }


    private List<SysMenuVo> getSAreaTree(String divisionId) throws UnsupportedEncodingException {
        String jsonStr = sysAreaService.jsonSAreaTree(URLEncoder.encode(divisionId, "UTF-8"));
        Gson gson = CreateGson.createGson();
        Type srItemsStandardType = new TypeToken<List<SysMenuVo>>() {
        }.getType();
        List<SysMenuVo> sysMenuList = gson.fromJson(jsonStr, srItemsStandardType);
        return sysMenuList;
    }
}
